com.alibaba
fastjson
1.2.83
完整的pom文件如下所示:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.7.15
com.example
FastJsonDemo
0.0.1-SNAPSHOT
FastJsonDemo
FastJsonDemo
1.8
org.springframework.boot
spring-boot-starter-web
com.alibaba
fastjson
1.2.83
org.projectlombok
lombok
1.18.28
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
2.7.15
package com.example.fastjsondemo.model;
import lombok.Data;
/**
* @author qx
* @date 2023/8/29
* @des
*/
@Data
public class Student {
private Long id;
private String name;
private Integer age;
}
package com.example.fastjsondemo.model;
import lombok.Data;
/**
* @author qx
* @date 2023/8/29
* @des
*/
@Data
public class School {
private String name;
private String address;
}
将对象生成json
/**
* 将一个对象转成Json
*/
@Test
void testToJson() {
Student student = new Student();
student.setId(1L);
student.setName("qx");
student.setAge(20);
String json = JSONObject.toJSONString(student);
// 输出{"age":20,"id":1,"name":"qx"}
System.out.println(json);
}
json转对象
/**
* json转对象
*/
@Test
void testToObject() {
String data = "{\"age\":20,\"id\":1,\"name\":\"qx\"}";
Student student = JSONObject.parseObject(data, Student.class);
// 输出Student(id=1, name=qx, age=20)
System.out.println(student);
}
根据键获取Json数据中的值
/**
* 获取json中的值
*/
@Test
void testAccessValue() {
String data = "{\"age\":20,\"id\":1,\"name\":\"qx\"}";
JSONObject jsonObject = JSONObject.parseObject(data);
String name = jsonObject.getString("name");
// 输出qx
System.out.println(name);
int age = jsonObject.getIntValue("age");
// 输出20
System.out.println(age);
}
package com.example.fastjsondemo.model;
import lombok.Data;
/**
* @author qx
* @date 2023/8/29
* @des
*/
@Data
public class Student {
private Long id;
private String name;
private Integer age;
private School school;
}
测试
对象转Json
@Test
void testToJson() {
Student student = new Student();
student.setId(1L);
student.setName("qx");
student.setAge(20);
School school = new School();
school.setName("广西大学");
school.setAddress("南宁西乡塘区");
student.setSchool(school);
String json = JSONObject.toJSONString(student);
// 输出{"age":20,"id":1,"name":"qx","school":{"address":"南宁西乡塘区","name":"广西大学"}}
System.out.println(json);
}
Json转对象
/**
* json转对象
*/
@Test
void testToObject() {
String data = "{\"age\":20,\"id\":1,\"name\":\"qx\",\"school\":{\"address\":\"南宁西乡塘区\",\"name\":\"广西大学\"}}";
Student student = JSONObject.parseObject(data, Student.class);
// 输出Student(id=1, name=qx, age=20, school=School(name=广西大学, address=南宁西乡塘区))
System.out.println(student);
}
获取Json中的某个值
/**
* 获取json中的值
*/
@Test
void testAccessValue() {
String data = "{\"age\":20,\"id\":1,\"name\":\"qx\",\"school\":{\"address\":\"南宁西乡塘区\",\"name\":\"广西大学\"}}";
JSONObject jsonObject = JSONObject.parseObject(data);
JSONObject school = jsonObject.getJSONObject("school");
String name = school.getString("name");
// 输出 广西大学
System.out.println(name);
}