(播放2.5)如何为Option的类型别名定义json格式?

编程入门 行业动态 更新时间:2024-10-28 08:28:12
本文介绍了(播放2.5)如何为Option的类型别名定义json格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 case class ClassA(myObjectType: TypeA.myTypeAlias) object ClassA { implicit def jsonFormat: Format[ClassA] = Json.format[ClassA] } object TypeA { type myTypeAlias = Option[String] }

我得到No implicit format for typeA.myObjectType available.

如何定义JSON格式?

How do you define the JSON Format ?

推荐答案

此错误来自 play.api.libs.json.JsMacroImpl.scala(播放2.5.0-RC2中的第164行)

This error comes from the automatic implicit generation macro in play.api.libs.json.JsMacroImpl.scala (line 164 in Play 2.5.0-RC2).

此代码在分析类型之前不会处理类型,因此甚至无法推断TypeA.myTypeAlias是Option.

This code doesn't dealias types before analyzing them, so it can't even infer that TypeA.myTypeAlias is an Option.

您可以做的一件事是指定一个隐式Format[myTypeAlias]:

One thing you can do is specify an implicit Format[myTypeAlias]:

object ClassA { implicit val myTypeAliasFormat: Format[TypeA.myTypeAlias] = Format.optionWithNull implicit def jsonFormat: Format[ClassA] = Json.format[ClassA] }

object TypeA { type myTypeAlias = Option[String] implicit val myTypeAliasFormat: Format[myTypeAlias] = Format.optionWithNull } object ClassA { import TypeA.myTypeAliasFormat implicit def jsonFormat: Format[ClassA] = Json.format[ClassA] }

请注意,它将把JSON null转换为None,如果缺少路径,则会产生错误,并将None序列化为JSON null.

Note that it will convert JSON null to None, yield an error if the path is missing, and serialize None as JSON null.

我相信,当使用类型别名和自动隐式生成与Json.format时,无法实现将缺少的路径解释为None并跳过序列化None的行为.如果您想要这种行为,则必须手动编写JSON Format.

I believe, it's not possible to achieve the behaviour to interpret missing paths as None, and skip serializing None, when using type aliases and automatic implicit generation with Json.format. You'd have to manually write a JSON Format if you want that behaviour.

更多推荐

(播放2.5)如何为Option的类型别名定义json格式?

本文发布于:2023-10-05 08:44:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467337.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:别名   何为   定义   类型   格式

发布评论

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

>www.elefans.com

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