Deserialization of case object in Scala with JSON4S
Asked Answered
P

2

9

I have some case classes defined like follows:

sealed trait Breed
case object Beagle extends Breed
case object Mastiff extends Breed
case object Yorkie extends Breed

case class Dog(name: String, breed: Breed)

I also have an endpoint defined with Scalatra:

post("/dog") {
  val dog = parsedBody.extract[Dog]
  ...
}

I'd like this JSON object:

{
  name: "Spike",
  breed: "Mastiff"
}

to deserialize to the appropriate instance of Dog. I'm struggling to figure out how to write a custom deserializer for Breed and register it with JSON4S.

Paul answered 14/10, 2015 at 21:27 Comment(0)
F
11

You need to write the serializer like below:

Serializer:

case object BreedSerializer extends CustomSerializer[Breed](format => (
    {
      case JString(breed) =>  breed match {
        case "Beagle" => Beagle
        case "Mastiff" => Mastiff
        case "Yorkie" => Yorkie
      }
      case JNull => null
    },
    {
      case breed:Breed => JString(breed.getClass.getSimpleName.replace("$",""))
    }))

Now, you will have to add this serialiser to the default formats.

import org.json4s.CustomSerializer
val serializers = List(BreedSerializer)
implicit lazy val serializerFormats: Formats = DefaultFormats ++ serializers

Hope this solves your problem.

Fachini answered 15/10, 2015 at 6:40 Comment(0)
R
4

You can create a CustomSerializer for Breed like you mentioned :

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization._

object BreedSerializer extends CustomSerializer[Breed]( format => ( 
  {
    case JString("Beagle")  => Beagle
    case JString("Mastiff") => Mastiff
    case JString("Yorkie")  => Yorkie
  }, {
    case Beagle  => JString("Beagle") 
    case Mastiff => JString("Mastiff")
    case Yorkie  => JString("Yorkie")
  }  
))

Which you can use as :

val json1 = """{ "name": "Spike", "breed": "Yorkie" }"""
val json2 = """{ "name": "Pluto", "breed": "Mastiff" }"""

implicit val json4sFormats = Serialization.formats(NoTypeHints) + BreedSerializer

val dog1 = parse(json1).extract[Dog] // Dog(Spike,Yorkie)
val dog2 = parse(json2).extract[Dog] // Dog(Pluto,Mastiff)
Raze answered 15/10, 2015 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.