【问题标题】:How to ignore field in Spray-json [Scala]如何忽略 Spray-json [Scala] 中的字段
【发布时间】: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。我也删不掉,因为不同的地方答案也不一样。

标签: json scala spray


【解决方案1】:

在 Scala 中,习惯上使用称为lens/lenses 的方法来处理或修改复杂的不可变对象。 Spray-json 有一些镜头:gistlibrary

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

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 2019-04-30
    • 2012-06-04
    • 1970-01-01
    • 2017-09-01
    • 2015-02-23
    • 1970-01-01
    • 2012-02-12
    相关资源
    最近更新 更多