我需要反序列化一些如下所示的JSON:
{ "states":
{ "Position" : { "x": 1, "y": 2, "z": 3 },
"Timestamp" : { "value" : 123 } }
}
名为Position和Timestamp的字段是要序列化的类的名称。
我目前能够反序列化的唯一方法是将此JSON转换为提升Web JSON理解的格式。例如:
{ "states": [
{ "jsonClass": "Position", "x": 1, "y": 2, "z": 3 },
{ "jsonClass": "Timestamp", "value" : 123 }
]}
formats
如下
implicit val formats = new DefaultFormats {
override val typeHintFieldName = "type"
override val typeHints = ShortTypeHints(List(classOf[Position], classOf[Timestamp]))
}
是否可以对顶层表单进行反序列化?
答案 0 :(得分:2)
使用杰克逊,然后:
case class Position(x: Int, y: Int, z: Int)
case class Timestamp(value: Int)
case class State(position: Position, timestamp: Timestamp)
case class States(states: Seq[State])
object Test extends App {
val mapper = new ObjectMapper with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true)
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
val states = mapper.readValue[Seq[States]]( """{
| "states": {
| "position" : { "x": 1, "y": 2, "z": 3 },
| "timestamp" : { "value" : 123 }
| }
|}""".stripMargin)
println(states)
}
给出
List(States(List(State(Position(1,2,3),Timestamp(123)))))
注1:在Json使用badgerfish表示法的情况下,配置行允许Jackson将{}视为单个元素数组
注意2:如果您有大写字段名称,请重命名案例类中的字段名称以匹配,例如case class State(Position: Position, Timestamp: Timestamp)