使用Play JSON API将数组读入自定义对象列表的最简单方法

问题描述:

我正在使用Play JSON API(最新版本; Play 2.4),将传入的JSON读取到对象中.

I'm working with Play JSON API (latest version; Play 2.4), reading incoming JSON into objects.

编写 JSON时,只要我有implicit val writes = Json.writes[CustomType],使用自定义对象列表绝对没有问题.

When writing JSON, there's absolutely no problem in using a list of custom objects, as long as I have implicit val writes = Json.writes[CustomType].

但是显然相反不是正确的,因为即使为*类型和列表项类型(使用Json.reads[Incoming]Json.reads[Item])都生成了Reads,以下内容也不起作用.自定义Reads实现是强制性的吗?还是我缺少明显的东西?使这项工作最简单的方法是什么?

But apparently the inverse is not true, as the following does not work even though Reads is generated for both top-level type and list item type (using Json.reads[Incoming] and Json.reads[Item]). Is custom Reads implementation mandatory? Or am I missing something obvious? What is the simplest way to make this work?

简化示例:

JSON:

{
  "test": "...",
  "items": [
     { "id": 44, "time": "2015-11-20T11:04:03.544" },
     { "id": 45, "time": "2015-11-20T11:10:10.101" }
  ]
}

与传入数据匹配的模型/DTO:

Models/DTOs matching the incoming data:

import play.api.libs.json.Json

case class Incoming(test: String, items: List[Item])

object Incoming {
  implicit val reads = Json.reads[Incoming]
}


case class Item(id: Long, time: String)

object Item {
  implicit val reads = Json.reads[Item]
}

控制器:

def test() = Action(parse.json) { request =>
  request.body.validate[Incoming].map(incoming => {
     // ... handle valid incoming data ...
  }).getOrElse(BadRequest)
}

编译器这样说:

No implicit format for List[models.Item] available.
[error]   implicit val reads = Json.reads[Incoming]
                       ^
No Json deserializer found for type models.Incoming. 
Try to implement an implicit Reads or Format for this type.
[error]     request.body.validate[Incoming].map(incoming => {

尝试在Incoming之前定义Item 的案例类和对象.查看此答案以获取更多信息: https://*.com/a/15705581