1、java转JSON
JSON.toJSONString() // 将java对象、java集合、Json对象转为jsonString
JSON.toJSON() // 将java对象、java集合转为json对象
3、JSON转Java
JSON.parse() // 将jsonString解析为jsonObject或者jsonArray
JSON.parseObject() // 将jsonString解析为javaObject或者jsonObject
JSON.parseArray() // 将jsonString解析为javaObjectList或者jsonArray
3、用到的jar包有
com.fasterxml.jackson.module jackson-module-scala_3 2.15.2 com.alibaba.fastjson2 fastjson2 2.0.38
4、具体代码实现
4.1、写一个类,代码如下:
package com.example.student20230710.domain; public class Student { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name=" + name + ", age=" + age + '}'; } }
4.2、JSON和String的相互转换,代码如下:
package com.example.student20230710.test; import com.alibaba.fastjson2.JSON; import com.example.student20230710.domain.Student; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class fastjson { public static void main(String[] args) throws SQLException, JsonProcessingException {// java转JSON // JSON.toJSONString() // 将java对象、java集合、Json对象转为jsonString // JSON.toJSON() // 将java对象、java集合转为json对象 // JSON转Java // JSON.parse() // 将jsonString解析为jsonObject或者jsonArray // JSON.parseObject() // 将jsonString解析为javaObject或者jsonObject // JSON.parseArray() // 将jsonString解析为javaObjectList或者jsonArray Student yyhstudent = new Student(); yyhstudent.setId(1); yyhstudent.setName("yyh"); yyhstudent.setAge(24); Student dystudent = new Student(); dystudent.setId(2); dystudent.setName("dy"); dystudent.setAge(24); Listlist = new ArrayList (); list.add(yyhstudent); list.add(dystudent); //对象转json,会存在顺序错了的问题(用的fastjson) String studentJson = JSON.toJSONString(yyhstudent); System.out.println("1------对象转json串:" +studentJson);//{"age":24,"id":1,"name":"yyh"} 顺序发生了变化 //对象转json,不会存在顺序错了的问题(用的jackson) String studentJson1 = new ObjectMapper().writeValueAsString(yyhstudent); System.out.println("2------对象转json串:" +studentJson1); //json转对象(用的fastjson) Student student1 = JSON.parseObject(studentJson,Student.class); System.out.println("3------json转对象:" +student1.toString()); // 集合转json(会出现单个对象顺序问题)(用的fastjson) String listJson =JSON.toJSONString(list); System.out.println("集合转json串:" + listJson); // 集合转json(不会出现单个对象顺序问题)(用的jackson) String listJson2 = new ObjectMapper().writeValueAsString(list);//对象转json,不会存在顺序错了的问题 System.out.println("集合转json串:" + listJson2); // json字符串转List