案例类只有一个字段时如何将json转为案例类

案例类只有一个字段时如何将json转为案例类

问题描述:

在 play 2.1 中读取用于将 Json 编组到对象.但是当案例类只有一个字段时,我怎么能做到这一点.适用于更多字段的成语不起作用,因为没有使用一个字段and".因此我没有得到 FunctionBuilder.

In play 2.1 reads are used to marshall Json to objects. But how can I do this when the case class has only one field. The ideom that works for more fields does not work, as with one field 'and' is not used. Thus I do not get a FunctionBuilder.

下面的代码给了我一个类型不匹配.我该如何解决这个问题?

The following code gives me a type mismatch. How can I fix this?

case class Data(stamm: Seq[String])


implicit val dataReads  = (
  (__  "stamm").read(Reads.list[String])
)(Data)

Json 组合器不适用于单字段案例类.

Json combinators doesn't work for single field case class.

Pascal(这个 API 的作者)在这里解释了这种情况https://groups.google.com/forum/?fromgroups=#!starred/游戏框架/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 A(value: List[Int])
val areads = (__  'value).read[List[Int]].map{ l => A(l) } // covariant map