我在SCALA中使用spray-json。 SPRAY-Github我想从json回答中排除(忽略)某些字段。什么是最佳做法?
package ru.steklopod
import org.scalatest.FunSuite
import ru.steklopod.entities.{Game, Helper}
import spray.json.{DefaultJsonProtocol, _}
trait MyJsonProtocol extends DefaultJsonProtocol {
implicit val gameFormat = new JsonWriter[Game] {
def write(g: Game): JsValue = {
JsObject(
"id" -> g.id.toJson,
"next_step" -> JsNumber(g.nextStep),
"won" -> g.won.toJson,
"finished" -> JsBoolean(g.finished),
"players" -> JsString(g.players),
"steps" -> JsNumber(g.steps),
"size" -> JsString(g.size),
"crosses_length_to_win" -> JsNumber(g.crossesLengthToWin),
"field" -> JsString(g.fieldPlay)
)
}
}
}
class JsonTest extends FunSuite with MyJsonProtocol {
test("JSON") {
val game = new Game(1, None, false, "1, 2", 0, Helper.ThreeByThree.toString, 3, "0, 0, 0, 0, 0, 0, 0, 0, 0")
val marshalled = game.toJson
println(marshalled)
}
}
最终的编组对象是:
{"players":"1, 2","size":"3, 3","field":"0, 0, 0, 0, 0, 0, 0, 0, 0","finished":false,"id":1,"next_step":1,"crosses_length_to_win":3,"steps":0,"won":null}
答案 0 :(得分:1)
在Scala中,习惯上使用称为lens/lenses的方法处理或修改复杂的不可变对象。喷雾json有一些镜头:gist和library。
对于您的解决方案来说,这可能太难了,您只需从JSON对象(JsObject.fields)修改几个字段,然后创建一个新的JSON对象。