gpt4 book ai didi

json - Spray-json反序列化嵌套对象

转载 作者:行者123 更新时间:2023-12-04 18:47:53 30 4
gpt4 key购买 nike

如何在Spray-json中正确反序列化嵌套对象?

    import spray.json._

case class Person(name: String)

case class Color(n: String, r: Int, g: Int, b: Int, p: Person)

object MyJsonProtocol extends DefaultJsonProtocol {

implicit object ColorJsonFormat extends RootJsonFormat[Color] {
def write(c: Color) = JsObject(
"color-name" -> JsString(c.n),
"Green" -> JsNumber(c.g),
"Red" -> JsNumber(c.r),
"Blue" -> JsNumber(c.b),
"person-field" -> JsObject("p-name" -> JsString(c.p.name))
)

def read(value: JsValue) = {
value.asJsObject.getFields("color-name", "Red", "Green", "Blue", "person-field") match {
case Seq(JsString(name), JsNumber(red), JsNumber(green), JsNumber(blue), JsObject(person)) =>
Color(name, red.toInt, green.toInt, blue.toInt, null) //gotta replace null with correct deserializer
case _ => throw new DeserializationException("Color expected")
}
}
}

}

import MyJsonProtocol._

val jsValue = Color("CadetBlue", 95, 158, 160, Person("guest")).toJson

jsValue.prettyPrint

val color = jsValue.convertTo[Color] //person is missing of course


在旁注中,如何使用Spray-json帮助序列化到字段映射(嵌套对象的嵌套映射)?

最佳答案

下面的示例演示JSON->抽象语法树-> Scala案例类,并返回自定义字段名称以及对可选案例类成员的支持。该示例来自https://github.com/spray/spray-json的Spray-json文档(版本1.2.5)。

package rando

import spray.json._

case class Color(name: String, red: Int, green: Int, blue: Int)

case class Team(name: String, color: Option[Color])

object MyJsonProtocol extends DefaultJsonProtocol {
implicit val colorFormat = jsonFormat(Color, "name", "r", "g", "b")
implicit val teamFormat = jsonFormat(Team, "name", "jersey")
}
import MyJsonProtocol._

object GoSox extends App {
val obj = Team("Red Sox", Some(Color("Red", 255, 0, 0)))
val ast = obj.toJson
println(obj)
println(ast.prettyPrint)
println(ast.convertTo[Team])
println("""{ "name": "Red Sox", "jersey": null }""".asJson.convertTo[Team])
println("""{ "name": "Red Sox" }""".asJson.convertTo[Team])
}

该示例在执行时输出以下内容:
Team(Red Sox,Some(Color(Red,255,0,0)))
{
"name": "Red Sox",
"jersey": {
"name": "Red",
"r": 255,
"g": 0,
"b": 0
}
}
Team(Red Sox,Some(Color(Red,255,0,0)))
Team(Red Sox,None)
Team(Red Sox,None)

关于json - Spray-json反序列化嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21691525/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com