0

How do you create a jackson custom serializer and use it in your program? The serializer is used to serialize data from a kafka stream, because my job fails if it encounters a null.

I tried the following to create a serializer.

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

I am trying to use it this way.

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)

}

I am getting an error saying that

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]
Srinivas
  • 2,010
  • 7
  • 26
  • 51

1 Answers1

0

Not sure if I answer your question. I provide the runnable code:

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)))
yiksanchan
  • 1,890
  • 1
  • 13
  • 37