使用JSON4S在Scala中对案例对象进行反序列化

使用JSON4S在Scala中对案例对象进行反序列化

本文介绍了使用JSON4S在Scala中对案例对象进行反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我定义了一些案例类,如下所示:

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)

我也有一个用Scalatra定义的端点:

I also have an endpoint defined with Scalatra:

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

我想要这个JSON对象:

I'd like this JSON object:

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

反序列化为Dog的适当实例.我正在努力弄清楚如何为Breed编写自定义反序列化器并将其注册到JSON4S.

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.

推荐答案

您需要编写如下的序列化器:

You need to write the serializer like below:

序列化器:

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.

这篇关于使用JSON4S在Scala中对案例对象进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:47