我正在使用json4s来处理我的Scala代码中的JSON对象。我想将JSON数据转换为内部表示。以下学习测试说明了我的问题:
"Polimorphic deserailization" should "be possible" in {
import org.json4s.jackson.Serialization.write
val json =
"""
|{"animals": [{
| "name": "Pluto"
| }]
|}
""".stripMargin
implicit val format = Serialization.formats(ShortTypeHints(List(classOf[Dog], classOf[Bird])))
val animals = parse(json) \ "animals"
val ser = write(Animals(Dog("pluto") :: Bird(canFly = true) :: Nil))
System.out.println(ser)
// animals.extract[Animal] shouldBe Dog("Pluto") // Does not deserialize, because Animal cannot be constructed
}
假设有一个JSON对象,其中包含一个动物列表。 Animal
是一种抽象类型,因此无法实例化。相反,我想解析JSON结构以返回 Dog
要么 Bird
对象。他们有不同的签名:
case class Dog(name: String) extends Animal
case class Bird(canFly: Boolean) extends Animal
因为它们的签名是不同的,所以可以在JSON对象中没有类Tag的情况下识别它们。 (确切地说,我收到的JSON结构不提供这些标签)。
我试图序列化Animal对象列表(参见代码)。结果是: Ser: {"animals":[{"jsonClass":"Dog","name":"pluto"},{"jsonClass":"Bird","canFly":true}]}
如您所见,在序列化时,json4s会添加class-tag jsonClass
。
如何反序列化不提供此类标记的JSON对象? 是否有可能通过扩展来实现这一目标 TypeHints
?
我也发现了类似的问题: [json4s]:提取不同对象的数组 一个解决方案,以某种方式使用泛型而不是子类。但是,如果我理解正确,此解决方案不允许简单地传递json对象并具有内部表示。相反,我需要选择不是的形式 None
(同时检查继承层次结构中所有可能的类型。这有点单调乏味,因为我在JSON结构中有不同深度的多个多态类。