在 Play2 和 Scala 中解析没有数据类型的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15643821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON in Play2 and Scala without Data Type
提问by Commander
{
"people": [
{
"name": "Hyman",
"age": 15
},
{
"name": "Tony",
"age": 23
},
{
"name": "Mike",
"age": 19
}
]
}
Thats a sample of the json I'm trying to parse through. I want to be able to do a foreach operation on each person and println their name and age.
那是我试图解析的 json 示例。我希望能够对每个人进行 foreach 操作并打印他们的姓名和年龄。
I know how to handle json arrays when it's a single item or a specific numbered item. I don't know how to iterate through all items.
我知道如何处理单个项目或特定编号项目的 json 数组。我不知道如何遍历所有项目。
Can anyone help me out?
谁能帮我吗?
回答by Julien Lafont
There are many ways to do this with the Play JSON Library. The main difference is the usage of Scala case class or not.
使用 Play JSON 库有很多方法可以做到这一点。主要区别在于是否使用 Scala 案例类。
Given a simple json
给定一个简单的 json
val json = Json.parse("""{"people": [ {"name":"Hyman", "age": 19}, {"name": "Tony", "age": 26} ] }""")
You can use case class and Json Macro to automatically parse the data
可以使用case类和Json宏来自动解析数据
import play.api.libs.json._
case class People(name: String, age: Int)
implicit val peopleReader = Json.reads[People]
val peoples = (json \ "people").as[List[People]]
peoples.foreach(println)
Or without case class, manually
或者没有案例类,手动
import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val personReader: Reads[(String, Int)] = (
(__ \ "name").read[String] and
(__ \ "age").read[Int]
).tupled
val peoples = (json \ "people").as[List[(String, Int)]]
peoples.foreach(println)
In other words, check the very complete documentation on this subject :) http://www.playframework.com/documentation/2.1.0/ScalaJson
换句话说,检查关于这个主题的非常完整的文档:) http://www.playframework.com/documentation/2.1.0/ScalaJson
回答by inmyth
If you don't have the object type or don't want to write a Reads, you can use .as[Array[JsValue]]
如果您没有对象类型或不想编写读取,则可以使用 .as[Array[JsValue]]
val jsValue = Json.parse(text)
val list = (jsValue \ "people").as[Array[JsValue]]
Then
然后
list.foreach(a => println((a \ "name").as[String]))
In the older version (2.6.x) it is possible to use .as[List[JsValue]]but newer versions only support Array.
在旧版本 (2.6.x) 中可以使用,.as[List[JsValue]]但新版本仅支持 Array。

