JSON是目前主流的前后端数据传输方式。默认情况下,当创建一个springboot项目时,添加了web依赖,这个依赖默认加入了jackson-databind作为JSON处理器,此时不需要添加额外的JSON处理器就能返回一段JSON了
创建一个Book实体类
package com.example.jsonexer.entity;
import lombok.Data;
import java.util.Date;
@Data
public class Book {
private String name;
private String author;
private Float price;
private Date publicationDate;
}
创建BookController,返回Book对象
@RestController
public class BookController {
@GetMapping("/book")
public Book book(){
Book book= new Book();
book.setAuthor("罗贯中");
book.setName("三国演义");
book.setPrice(30f);
book.setPublicationDate(new Date());
return book;
}
}
在浏览器中输入“http://localhost:8080/book”,即可看到返回的JSON数据,如图所示
FastJson使用
package com.example.jsonexer.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student {
private int id;
private String name;
private int age;
}
package com.example.jsonexer.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
测试:
package com.example.jsonexer;
import com.alibaba.fastjson.JSON;
import com.example.jsonexer.entity.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JsonexerApplicationTests {
@Test
public void testJson() {
Student student = new Student(0,"zhangsan",22);
System.out.println(JSON.toJSONString(student));
}
}
输出结果:
{"age":22,"id":0,"name":"zhangsan"}
输出的json格式与类Student中定义的属性其实是不一致的,这个其实不影响我们生成以及后面的解析,因为他有严格的get和set方法定义。
@Test
public void testJson2(){
List<Student> stus = new ArrayList<Student>();
for(int i = 0; i < 5; i++){
Student student = new Student(i,"Student" + i,18 + i);
stus.add(student);
}
System.out.println(JSON.toJSONString(stus));
}
输出结果:
[{"age":18,"id":0,"name":"Student0"},{"age":19,"id":1,"name":"Student1"},{"age":20,"id":2,"name":"Student2"},{"age":21,"id":3,"name":"Student3"},{"age":22,"id":4,"name":"Student4"}]
@Test
public void testJson3(){
List<Teacher> teachers = new ArrayList<>();
long time = System.currentTimeMillis();
for(int i = 0; i < 10; i++){
Teacher teacher = new Teacher(i,"Teacher" + i);
List<Student> stus = new ArrayList<Student>();
for(int j = 0; j < 4; j++){
Student s = new Student(j,"Student" + j, 18 + j);
stus.add(s);
}
teacher.setStudents(stus);
teachers.add(teacher);
}
String json = JSON.toJSONString(teachers);
System.out.println("fastjson= " + json);
}
输出结果:
fastjson= [{"id":0,"name":"Teacher0","students":[{"age":18,"id":0,"name":"Student0"},{"age":19,"id":1,"name":"Student1"},