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