使用Gson--谷歌
导入依赖
//Gson pom依赖
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
示例
//创建java对象
Person person = new Person();
person.setUname("zhangsan");
person.setAge(20);
person.setSex("男");
//创建Gson对象
Gson gson = new Gson();
//java对象转化成Json格式的字符串
String jsonString = gson.toJson(Person);
//Json格式的字符串转换成java对象
Person p = gson.fromJson(jsonString,Person.class);
使用FastJson--阿里
导入依赖
//fastJson pom依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
示例
//创建java对象
Person person = new Person();
person.setUname("zhangsan");
person.setAge(20);
person.setSex("男");
//Java对象转化成Json格式的字符串
//用法:JSONObject.toJsonString(Java对象);
String jsonString = JSONObject.toJSONString(Person);
//Json格式的字符串转换成Java对象
//用法:JSONObject.toJavaObject(JSON字符串,Java对象.class)
Person p = JSONObject.toJavaObject(jsonString,Person.class);
//Json格式字符串转Json对象
//用法:JSONObject.parseObject(JSON字符串)
JSONObject jsonObject = JSONObject.parseObject(jsonString);
Jackson ---Spring Mvc内置解析
导入依赖
jackson核心依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.1</version>
</dependency>
示例
//创建java对象
Person person = new Person();
person.setUname("zhangsan");
person.setAge(20);
person.setSex("男");
// 创建ObjectMapper对象。
ObjectMapper mapper = new ObjectMapper();
// Java对象转Json格式字符串
jsonString = mapper.writeValueAsString(person);
// Json格式字符串转Java对象。
Person p= mapper.readValue(jsonString, Person.class);