如何在Scala中反序列化类型和值要映射的JSON对象



我需要反序列化一些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]))
}

是否可以反序列化顶部形式?

Using Jackson, then:

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)))))

注意:在Json使用badgerfish符号 的情况下,配置行允许Jackson将{}视为单个元素数组。

注意2:如果您有大写的字段名,请重命名大小写类中的字段名以匹配,例如case class State(Position: Position, Timestamp: Timestamp)

相关内容

  • 没有找到相关文章