如何在Play 2.1中将案例类与Json序列化/反序列化 [英] How to serialize/deserialize case classes to/from Json in Play 2.1

查看:84
本文介绍了如何在Play 2.1中将案例类与Json序列化/反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些案例类与Json进行序列化/反序列化...并且在处理仅具有一个字段的案例类时遇到了麻烦(我使用的是Play 2.1):

I'm trying to serialize/deserialize some case classes to/from Json... and I've troubles when dealing with case classes with just one field (I'm using Play 2.1):

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class MyType(type: String)

object MyType {

  implicit val myTypeJsonWrite = new Writes[MyType] {
    def writes(type: MyType): JsValue = {
      Json.obj(
        "type" -> MyType.type
      )
    }
  }

  implicit val myTypeJsonRead = (
    (__ \ 'type).read[String]
  )(MyType.apply _)
}

上面的代码始终会生成以下错误消息:

The code above always generates the following error message:

[error] /home/j3d/Projects/test/app/models/MyType.scala:34: overloaded method value read with alternatives:
[error]   (t: String)play.api.libs.json.Reads[String] <and>
[error]   (implicit r: play.api.libs.json.Reads[String])play.api.libs.json.Reads[String]
[error]  cannot be applied to (String => models.MyType)
[error]     (__ \ 'method).read[String]
[error]                        ^

我知道...只包含一个字符串的case类没有多大意义...但是我需要对一个case类进行序列化/反序列化,该类与我从外部库中获得的上述类非常相似.

I know... a case class that contains just a string does not make much sense... but I need to serialize/deserialize a case class very similar to the one I described above that comes from an external library.

有什么主意吗?我想念什么吗?任何帮助将不胜感激...我快疯了:-(谢谢.

Any idea? Am I missing something? Any help would be really appreciated... I'm getting crazy :-( Thanks.

推荐答案

Json组合器不适用于Play 2.1中的单个字段案例类(在2.2中应该可行)

Json combinators doesn't work for single field case class in Play 2.1 (it should be possible in 2.2)

Pascal(此API的编写者)已在此处 https://groups.google.com/forum/?fromgroups=#!starred/play-framework/hGrveOkbJ6U

Pascal (writer of this API) has explained this situation here https://groups.google.com/forum/?fromgroups=#!starred/play-framework/hGrveOkbJ6U

有些可行的解决方法,例如以下一种方法:

There are some workarounds which works, like this one:

case class MyType(value: String)
val myTypeRead = (__ \ 'value).read[String].map(v => MyType(v)) // covariant map

ps:type是Scala中的关键字,不能用作参数名称(但我认为这仅用于此示例)

ps: type is a keyword in Scala, it can't be used as parameter name (but I assume it's just for this example)

播放2.3.X尚不需要此解决方法.宏可以正常工作.

edit: This workaround is not yet required with play 2.3.X. The macro works fine.

这篇关于如何在Play 2.1中将案例类与Json序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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