Deserialization of case object in Scala with JSON4S

时光毁灭记忆、已成空白 提交于 2019-11-29 10:40:16

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!