简体   繁体   English

Play 2.3 Scala - 如何在没有参考模态类的情况下验证 json

[英]Play 2.3 Scala - How to validate json without a reference modal class

I've seen many examples with pretty much everything one can need to understand how to validate json representation of a given simple model.我已经看过许多示例,其中包含了解如何验证给定简单模型的 json 表示所需的几乎所有内容。 Official play documentation is very specific on the subject, covering from simple validations to transformers and combinators.官方 play 文档对这个主题非常具体,涵盖了从简单的验证到转换器和组合器。

I'm just wondering how can I check json againts a given data type structure, like:我只是想知道如何检查给定数据类型结构的 json,例如:

{
  title : "title1",
  tags  : ["funny", "others"],
  props : [
    { prop1: "val1" },
    { prop2: "val2" }
  ]
}

I'd like to check the previous json example, to validate if it has this structure:我想检查之前的 json 示例,以验证它是否具有以下结构:

title: String
tags:  Array[String]
props: Array[(String->String]  // ???

This is of course a simplification, since a case class would be as simple as:这当然是一种简化,因为案例类将像以下一样简单:

case class Example1(title: String, tags: Array[String], props: Array[???])

As you can see, my questions has two parts: - first, I want to properly use validation/transformation/reads or whatever API Play 2.3.x is ment to perform that kind of json validation without a model - second, how to specify an array of simple key/value objects如您所见,我的问题有两个部分: - 首先,我想正确使用验证/转换/读取或任何 API Play 2.3.x 来执行这种没有模型的 json 验证 - 第二,如何指定一个简单的键/值对象数组

Validation with Reads does not require a model class. 使用读取进行验证不需要模型类。

val json = { ... }
val titleMustBeString: Reads[String] = (JsPath \ "title").read[String]
json.validate[String](titleMustBeString) match {
  case title: JsSuccess[String] => println(s"Title: $title")
  case err: JsError => println("Invalid json")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM