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

编程入门 行业动态 更新时间:2024-10-17 02:47:09
本文介绍了使用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中对案例对象进行反序列化

本文发布于:2023-07-14 14:45:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1105098.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中对   对象   案例   序列化   JSON4S

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!