反序列化Scala案例类时,如何跳过Jackson中的包装JSON对象?

我有来自外部系统的数据,其格式如下:

{
  "type": "text","data": {
    "text": "Here's some text"
  }
}

type中有许多值,data中有不同的字段,所有值都有相应的案例类,应将其反序列化为顶级结构的一部分,例如:

case class TopLevel(parts: Part)
sealed trait Part
case class Text(text: String) extends Part
case class Image(url: String,...) extends Part
...

如何在不围绕Part创建包装的情况下以一种不错的方式实现此目的?

hjh198966 回答:反序列化Scala案例类时,如何跳过Jackson中的包装JSON对象?

您需要为您的类型创建一个自定义序列化程序。像这样:

import org.json4s.{CustomSerializer,DefaultFormats,Extraction,JObject,JString}
import org.json4s.jackson.JsonMethods.parse
import org.json4s.jackson.Serialization

class PartSerializer extends CustomSerializer[Part](format => ( {
  case JObject(("type",JString(typeString)) :: ("data",obj) :: Nil) =>
    implicit val f = format

    typeString match {
      case "text" =>
        Extraction.extract[Text](obj)
      case "image" =>
        Extraction.extract[Image](obj)
    }
},{
  case text: Text =>
    implicit val f = format

    JObject(List(
      ("type",JString("text")),("data",JObject(List(
        ("text",JString(text.text))))
      ),))
  case img: Image =>
    implicit val f = format

    JObject(List(
      ("type",JString("image")),JObject(List(
        ("url",JString(img.url))))
      ),))
}
))

然后您可以像这样使用它:

implicit val formats = DefaultFormats + new PartSerializer()

// Parse JSON
val part = Extraction.extract[Part](parse(json))
// Generate JSON
val json = Serialization.write(part)

如果将Part数据嵌入外部对象中,这也将起作用。

本文链接:https://www.f2er.com/3161274.html

大家都在问