(播放2.5)如何为Option的类型别名定义json格式? [英] (Play 2.5) How do you define json format for type alias of an Option?

查看:105
本文介绍了(播放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 ?

推荐答案

此错误来自

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.myTypeAliasOption.

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格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆