0

您如何创建杰克逊自定义序列化程序并在您的程序中使用它?序列化器用于序列化来自 kafka 流的数据,因为如果遇到空值,我的作业将失败。

我尝试了以下方法来创建序列化程序。

import org.json4s._
import org.json4s.jackson.JsonMethods._

case class Person(
                   val user: Option[String]
                 )

object PersonSerializer extends CustomSerializer[Person](formats => ( {
  case JObject(JField("user", JString(user)) :: Nil) => Person(Some(user))
  case JObject(JField("user", null) :: Nil) => Person(None)
},
  {
  case Person(Some(user)) => JObject(JField("user", JString(user)) :: Nil)
  case Person(None) => JObject(JField("user", JString(null)) :: Nil)
}))

我正在尝试以这种方式使用它。

object ConvertJsonTOASTDeSerializer extends App
{

  case class Address(street : String, city : String)
  case class PersonAddress(name : String, address : Address)

  val testJson1 =
    """
{ "user": null,
  "address": {
    "street": "Bulevard",
    "city": "Helsinki",
    "country": {
    "code": "CD" }
  },
  "children": [
    {
      "name": "Mary",
      "age": 5,
      "birthdate": "2004-09-04T18:06:22Z"
    },
    {
      "name": "Mazy",
      "age": 3
    }
  ]
}
"""

  implicit var formats : Formats = DefaultFormats + PersonSerializer

  val output = parse(testJson1).as[Person]

  println(output.user)

}

我收到一条错误消息

Error:(50, 35) No JSON deserializer found for type com.examples.json4s.Person. Try to implement an implicit Reader or JsonFormat for this type.
  val output = parse(testJson1).as[Person]
4

1 回答 1

0

不确定我是否回答你的问题。我提供了可运行的代码:

import org.json4s._
import org.json4s.jackson.JsonMethods._

case class Person(
    user: Option[String],
    address: Address,
    children: List[Child]
)

case class Address(
    street: String,
    city: String,
    country: Country
)

case class Country(
    code: String
)

case class Child(
    name: String,
    age: Int
)

val s =
"""
{ "user": null,
  "address": {
    "street": "Bulevard",
    "city": "Helsinki",
    "country": {
    "code": "CD" }
  },
  "children": [
    {
      "name": "Mary",
      "age": 5,
      "birthdate": "2004-09-04T18:06:22Z"
    },
    {
      "name": "Mazy",
      "age": 3
    }
  ]
}
"""

implicit val formats : Formats = DefaultFormats
parse(s).extract[Person] // Person(None,Address(Bulevard,Helsinki,Country(CD)),List(Child(Mary,5), Child(Mazy,3)))
于 2018-09-13T04:16:02.313 回答