JSON数据
定义:json是一种轻量级的前端后端以及网络传输的数据交换格式,就是一串字符串,只不过元素会使用特定的符号标注。 {} 双括号表示对象,[] 中括号表示数组,”” 双引号内是属性或值,: 冒号表示后者是前者的值(这个值可以是字符串、数字、也可以是另一个数组或对象)。
常见的JSON格式
JSON对象
JSON对象里面包含数组
后端常用的处理JSON的方式
我这里用的是用fastjson这个jar包来处的,这个方式挺方便的。
添加依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
代码实现:
public class TestDemo {
public static void main(String[] args) {
Student student1 = new Student("123","SDC","女");
Student student2 = new Student("321","CDS","男");
Student student3 = new Student("456","VFV","男");
Student student4 = new Student("654","BJC","女");
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
Group group1 = new Group("1","软件工程1班",list);
//对象转成JSON数据
String str1 = JSON.toJSONString(group1);
String str2 = JSON.toJSONString(list);
System.out.println(str1);
System.out.println(str2);
//JSON数据转为具体的对象
Student student = JSONObject.parseObject(str1,Student.class);
System.out.println(student.toString());
//json字符串转换为map
Map<Group,List<Student>> map = JSONObject.parseObject(str2, HashMap.class);
}
}
总结
json数据格式其实很好理解,也规范了前后台的数据交互格式,提高了我们的开发效率。