【发布时间】:2018-11-18 06:10:26
【问题描述】:
我在 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}
【问题讨论】:
-
你能修改
implicit val gameFormat吗?(只需删除你在输出中没有的文件)。 -
可以,但我需要自定义字段名称。
crossesLengthToWin必须是crosses_length_to_win。我也删不掉,因为不同的地方答案也不一样。