Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

json - Deserialization of case object in Scala with JSON4S

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...