本文介绍了使用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中对案例对象进行反序列化
发布评论