在java里面无法直接解析JSON格式的字符串或文本,这时候我们就需要一个解析json格式的库,我们这里用fastjson,接下来的代码操作如下:
1、导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.31</version>
</dependency>
2、解析json内容
import com.alibaba.fastjson.{JSON, JSONArray}
object Demo10JSON {
def main(args: Array[String]): Unit = {
val jsonStr =
"""
|[
| {
| "name":"张三",
| "age":23,
| "sex":"男"
| },
| {
| "name":"李四",
| "age":24,
| "sex":"男"
| }
|]
|""".stripMargin
//使用fastjson解析json格式数据
val users: JSONArray = JSON.parseArray(jsonStr)
//解析数据
//自定义类的字段名和类型需要和json字符串中保持一致
//classOf :scala中获取类对象的方法
val user: User = users.getObject(1, classOf[User])
println(user)
println(user.getName)
//一次获取JSON里面所有内容
for (i <- 0 until(users.size())){
val user: User = users.getObject(i, classOf[User])
println(s"第${i}个JSON元素内容为:\n姓名:${user.getName},\n年龄:${user.getAge},\n性别:${user.getSex}")
}
}
}
注意写JSON的时候要导包
User类:
public class User {
private String name;
private Long age;
private String sex;
public User(String name, Long age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}