java中常见的JSON格式转换方法
来源:https://blog.csdn.net/qq_42688149/article/details/122275540
1 JsonLib示例
package com.jsonDemo;
import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* @author LanceQ
* @date 2022年01月01日 15:40
*/
public class JsonLibDemo {
public static void main(String[] args) {
jsonTest();
}
private static void jsonTest() {
//java序列化为json
Student student = Student.getStudent();
JSONObject jsonObject = JSONObject.fromObject(student);
System.out.println("json string");
System.out.println(jsonObject.toString());
//Json反序列化为java
//如果对象中含有复杂对象,如List、Map或自定义javaBean,
// 需要使用一下的classMap,否则转换过程中会报错
Map<String,Class> classMap=new HashMap<>();
classMap.put("stuObject",Student.class);
student=(Student)JSONObject.toBean(jsonObject,Student.class,classMap);
System.out.println("java Object");
System.out.println(student);
System.out.println(student.getId());
System.out.println(student.getName());
System.out.println(student.getSex());
}
}
运行结果
json string
{"teacher":{"name":"老赵","id":888},"sex":"男","name":"小明","id":1}
java Object
Student{id=1, name='小明', sex='男', teacher=Teacher{id=888, name='老赵'}}
1
小明
男
2 Jackson示例
package com.jsonDemo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author LanceQ
* @date 2022年01月01日 21:09
*/
public class JacksonDemo {
public static void main(String[] args) {
String jsonString=null;
try {
Map jsonMap=new HashMap();
ObjectMapper mapper = new ObjectMapper();
Student student = Student.getStudent();
jsonMap.put("param1","value1");
jsonMap.put("param2","value2");
jsonMap.put("student",student);
jsonString= mapper.writeValueAsString(jsonMap);
System.out.println("Json String");
System.out.println(jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//反序列化
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(jsonString);
Map jsonMap = objectMapper.readValue(jsonString, Map.class);
System.out.println("json Object");
System.out.println(jsonMap);
Object student = jsonMap.get("student");
System.out.println(student);
System.out.println(jsonMap.get("param1"));
System.out.println(jsonMap.get("param2"));
System.out.println("----------------");
System.out.println(root.get("student"));
System.out.println(root.get("student").get("id"));
System.out.println(root.get("student").get("teacher"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果
Json String
{"student":{"id":1,"name":"小明","sex":"男","teacher":{"id":888,"name":"老赵"}},"param1":"value1","param2":"value2"}
json Object
{student={id=1, name=小明, sex=男, teacher={id=888, name=老赵}}, param1=value1, param2=value2}
{id=1, name=小明, sex=男, teacher={id=888, name=老赵}}
value1
value2
----------------
{"id":1,"name":"小明","sex":"男","teacher":{"id":888,"name":"老赵"}}
1
{"id":888,"name":"老赵"}
3 Gson示例
package com.jsonDemo;
import com.google.gson.Gson;
/**
* @author LanceQ
* @date 2022年01月01日 18:16
*/
public class GsonDemo {
public static void main(String[] args) {
String jsonString=null;
//java序列化为json
Student student = Student.getStudent();
Gson gson = new Gson();
jsonString=gson.toJson(student);
System.out.println("json String");
System.out.println(jsonString);
//json反序列化为java
student=gson.fromJson(jsonString,student.getClass());
System.out.println("java Object");
System.out.println(student);
System.out.println(student.getId());
System.out.println(student.getName());
System.out.println(student.getSex());
System.out.println(student.getTeacher().getId());
System.out.println(student.getTeacher().getName());
}
}
运行结果
json String
{"id":1,"name":"小明","sex":"男","teacher":{"id":888,"name":"老赵"}}
java Object
Student{id=1, name='小明', sex='男', teacher=Teacher{id=888, name='老赵'}}
1
小明
男
888
老赵
4 Fast示例
package com.jsonDemo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @author LanceQ
* @date 2022年01月01日 21:53
* 以上几款开源的 JSON 工具库的性能也并不是完全一样的,其速度关系是:
* Fastjson > Gson > Jackson> Json-lib
* https://www.json.org/json-en.html
*/
public class FastDemo {
public static void main(String[] args) {
String jsonString=null;
//java序列化为java
Student student = Student.getStudent();
jsonString=JSON.toJSONString(student);
System.out.println("json String");
System.out.println(jsonString);
//json反序列化为java
Student student1 = JSON.parseObject(jsonString, Student.class);
System.out.println("java Object");
System.out.println(student1);
System.out.println(student1.getId());
System.out.println(student1.getName());
System.out.println(student1.getTeacher());
System.out.println("-----------------------------------");
JSONObject jsonObject = JSON.parseObject(jsonString);
System.out.println(jsonObject.getInteger("id"));
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getJSONObject("teacher").get("id"));
}
}
运行结果
json String
{"id":1,"name":"小明","sex":"男","teacher":{"id":888,"name":"老赵"}}
java Object
Student{id=1, name='小明', sex='男', teacher=Teacher{id=888, name='老赵'}}
1
小明
Teacher{id=888, name='老赵'}
-----------------------------------
1
小明
888
5 实体类
package com.jsonDemo;
/**
* @author LanceQ
* @date 2022年01月01日 15:58
*/
public class Student {
private int id;
private String name;
private String sex;
private Teacher teacher;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", teacher=" + teacher +
'}';
}
public static Student getStudent(){
Student student = new Student();
student.setId(001);
student.setName("小明");
student.setSex("男");
Teacher teacher = new Teacher();
teacher.setId(888);
teacher.setName("老赵");
student.setTeacher(teacher);
return student;
}
}
package com.jsonDemo;
/**
* @author LanceQ
* @date 2022年01月01日 18:19
*/
public class Teacher {
private int id;
private String name;
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;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
6 依赖
<!-- json转实体类 fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<!-- json转实体类 jsonlib-->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- json转实体类gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!--Jackson包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
java中常见的JSON格式转换方法:
import net.sf.json.JSONArray; //用于集合或数组
import net.sf.json.JSONObject; //用于对象
JSONObject object = new JSONObject();
1.把java 对象列表转换为json对象数组,并转为字符串
JSONArray array = JSONArray.fromObject(userlist);
String jsonstr = array.toString();
2.把java对象转换成json对象,并转化为字符串(好像是map)
JSONObject object = JSONObject.fromObject(invite);
String str=object.toString();
3.把JSON字符串转换为JAVA 对象数组
String personstr = getRequest().getParameter("persons");
JSONArray json = JSONArray.fromObject(personstr);
List<InvoidPerison> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);
4.把JSON字符串转换为JAVA 对象
JSONObject jsonobject = JSONObject.fromObject(str);
PassportLendsEntity passportlends = null;
try {
//获取一个json数组
JSONArray array = jsonobject.getJSONArray("passports");
//将json数组 转换成 List<PassPortForLendsEntity>泛型
List<PassPortForLendsEntity> list = new ArrayList<PassPortForLendsEntity>();
for (int i = 0; i < array.size(); i++) {
JSONObject object = (JSONObject)array.get(i);
PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object,
PassPortForLendsEntity.class);
if(passport != null){
list.add(passport);
}
}