如何忽略 Spray-json [Scala] 中的字段

How to ignore field in Spray-json [Scala]

我在 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}

在 Scala 中,通常使用一种称为 lens/lenses. There are some lens for spray-json: gist and library 的方法来处理或修改复杂的不可变对象。

也许这对您的解决方案来说太难了,您可以只修改 JSON 对象 (JsObject.fields) 中的几个字段,然后创建一个新的 JSON 对象。