Play框架:如何在JSON中对枚举进行序列化/反序列化 [英] Play Framework: How to serialize/deserialize an enumeration to/from JSON
本文介绍了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中对枚举进行序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文