在Play2和Scala中解析JSON而没有数据类型

在Play2和Scala中解析JSON而没有数据类型

本文介绍了在Play2和Scala中解析JSON而没有数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

{
  "people": [
    {
      "name": "Jack",
      "age": 15
    },
    {
      "name": "Tony",
      "age": 23
    },
    {
      "name": "Mike",
      "age": 19
    }
  ]
}

那是我试图解析的json的样本.我希望能够对每个人进行一次foreach操作,并打印出他们的姓名和年龄.

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数组.我不知道如何遍历所有项目.

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播放库可以通过多种方式进行.主要区别在于是否使用了Scala案例类.

There are many ways to do this with the Play JSON Library. The main difference is the usage of Scala case class or not.

给出一个简单的json

Given a simple json

val json = Json.parse("""{"people": [ {"name":"Jack", "age": 19}, {"name": "Tony", "age": 26} ] }""")

您可以使用案例类和Json Macro来自动解析数据

You can use case class and Json Macro to automatically parse the data

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)

或者没有案例类,手动

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)

换句话说,请查看有关此主题的非常完整的文档:) http://www.playframework.com/documentation/2.1.0/ScalaJson

In other words, check the very complete documentation on this subject :)http://www.playframework.com/documentation/2.1.0/ScalaJson

这篇关于在Play2和Scala中解析JSON而没有数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:54