0

我能够对像这样的简单 json 结构执行简单的验证:

object RestTest extends Controller {

  case class Address(street: String,
                     number: Int)

  case class Person(name: String,
                    age: Int,
                    address: Address)

  implicit  val address = Json.reads[Address]
  implicit val rds = Json.reads[Person]

  def restTest = Action(parse.json) {
    request =>

      request.body.validate[Person].map {
          case person => Ok(Json.obj("e" -> 0, "message" -> ("The name is: " + person.name + " and he lives in " + person.address.street)))
        }.recoverTotal(e => Ok("e" -> 1)
      }
}

现在我有以下包含数组的结构,但到目前为止我无法正确验证它。我尝试了许多不同的方法,但我不断收到编译错误。

case class SecondStructure(index: Int)

case class EntryStructure(field1: String,
                  muSecondJsonArray: List[SecondStructure])

case class MyJsonArray(allEntries: List[EntryStructure])

我怎样才能验证这个json?

谢谢

4

1 回答 1

2

首先,确保您使用的是最新的 Play 2.1.1 版本。使用单个字段验证案例类时,早期版本存在问题。之后,它应该一切正常 - 请参见下面的示例:

object JsonTest {
  case class SecondStructure(index: Int)

  case class EntryStructure(field1: String, muSecondJsonArray: List[SecondStructure])

  case class MyJsonArray(allEntries: List[EntryStructure])

  // Use the macro "inception" feature to automatically build your Readers.
  implicit val ssReads = Json.reads[SecondStructure]
  implicit val esReads = Json.reads[EntryStructure]
  implicit val arrayReads = Json.reads[MyJsonArray]

  // Defining an example instance...
  val testArray = MyJsonArray(
    List(
      EntryStructure("foo", List(SecondStructure(1), SecondStructure(2))),
      EntryStructure("bar", List(SecondStructure(3), SecondStructure(4)))))

  // And the equivilant JSON structure...
  val testJson = Json.obj("allEntries" ->
    Json.arr(
      Json.obj("field1" -> "foo", "muSecondJsonArray" -> Json.arr(
        Json.obj("index" -> 1), Json.obj("index" -> 2))),
      Json.obj("field1" -> "bar", "muSecondJsonArray" -> Json.arr(
        Json.obj("index" -> 3), Json.obj("index" -> 4)))))

  testJson.validate[MyJsonArray].map {
    case foo if foo == testArray => println("Okay, we're good!")
  }
}
于 2013-06-05T19:40:11.670 回答