本文介绍了Play 框架:如何将枚举序列化/反序列化到/从 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于以下枚举...
object MyEnum extends Enumeration {
type MyEnum = Value
val Val1 = Value("val1")
val Val2 = Value("val2")
val ValN = Value("valN")
implicit val myEnumFormat = new Format[MyEnum] {
def reads(json: JsValue) = MyEnum.withName(json.as[String].value) // doesn't compile
def writes(myEnum: MyEnum) = JsString(myEnum.toString)
}
}
...我需要将它序列化/反序列化到/从 JSON.myEnumFormat
无法编译,我总是收到以下错误消息:
... I need to serialize/deserialize it to/from JSON. myEnumFormat
does not compile and I always get the following error message:
type mismatch;
[error] found : models.MyEnum.Value
[error] required: play.api.libs.json.JsResult[models.MyEnumValue]
[error] Note: implicit value myEnumFormat is not applicable here because it comes after the application point and it lacks an explicit result type
[error] def reads(json: JsValue) = MyEnum.withName(json.as[JsString].value)
我错过了什么吗?
推荐答案
尝试将其更改为
def reads(json: JsValue) = JsSuccess(MyEnum.withName(json.as[String].value))
这篇关于Play 框架:如何将枚举序列化/反序列化到/从 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!