- 添加依赖
- jackson依赖
- 其它常用的工具包依赖
- 封装的JsonMapper类
- 备注的待测试实体类
- User.java
- Student.java
- 测试代码
- 对象转换成Json
- Json转换成对象
- Json与List对象互转
- Json与Map对象互转
- Json与对象在转换中遇到空属性
在JavaWeb开发中,经常会涉及到相关的json与对象的互相转化问题,下面我就将其转化的过程中可能遇到的情况一一写出。
添加依赖
jackson依赖
<!--jackson-->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
其它常用的工具包依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
封装的JsonMapper类
package com.lyc.demo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;
@Slf4j
public class JsonMapper {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
//FAIL_ON_UNKNOWN_PROPERTIES在序列化的时候,如果遇到不认识的字段的处理方式
//默认启用特性,这意味着在遇到未知属性时抛出JsonMappingException。在引入该特性之前,这是默认的默认设置。
objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
//FAIL_ON_EMPTY_BEANS决定了在没有找到类型的存取器时发生了什么(并且没有注释表明它是被序列化的)。如果启用(默认),
// 将抛出一个异常来指明这些是非序列化类型;如果禁用了,它们将被序列化为空对象,即没有任何属性。
//请注意,这个特性只对那些没有任何识别注释的“空”bean产生影响(如@json序列化):那些有注释的bean不会导致抛出异常。
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
//过滤类的属性id
objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
//在序列化时,只有那些值为null或被认为为空的值的属性才不会被包含在内。
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
}
/**
* 对象转换成json
* @param obj
* @param <T>
* @return
*/
public static <T>String objectToJson(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to Json error",e);
e.printStackTrace();
return null;
}
}
/**
* 对象转换成格式化的json
* @param obj
* @param <T>
* @return
*/
public static <T>String objectToJsonPretty(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to Json error",e);
e.printStackTrace();
return null;
}
}
/**
* 将json转换成对象Class
* @param src
* @param clazz
* @param <T>
* @return
*/
public static <T>T jsonToObject(String src,Class<T> clazz){
if(StringUtils.isEmpty(src) || clazz == null){
return null;
}
try {
return clazz.equals(String.class) ? (T) src : objectMapper.readValue(src,clazz);
} catch (Exception e) {
log.warn("Parse Json to Object error",e);
e.printStackTrace();
return null;
}
}
/**
* 将json转换成对象TypeReference
* @param src
* @param typeReference
* @param <T>
* @return
*/
public static <T>T jsonToObject(String src, TypeReference<T> typeReference){
if(StringUtils.isEmpty(src) || typeReference == null){
return null;
}
try {
return (T)(typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
} catch (Exception e) {
log.warn("Parse Json to Object error",e);
e.printStackTrace();
return null;
}
}
/**
* 将json转换成对象
* @param src
* @param collectionClass
* @param elementClasses
* @param <T>
* @return
*/
public static <T>T jsonToObject(String src, Class<?> collectionClass,Class<?>... elementClasses){
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
try {
return objectMapper.readValue(src,javaType);
} catch (Exception e) {
log.warn("Parse Json to Object error",e);
e.printStackTrace();
return null;
}
}
}
备注的待测试实体类
User.java
package com.lyc.demo;
import lombok.*;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
}
Student.java
package com.lyc.demo;
import lombok.*;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student {
//id
private int id;
//姓名
private String name;
//年龄
private Integer age;
//编号
private String no;
}
测试代码
对象转换成Json
package com.lyc.demo;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
@Slf4j
public class ObjectToJsonTest {
private User user;
@Before
public void testBefore(){
user = User.builder()
.id(1)
.name("zhangsan")
.build();
}
/**
* 将对象转换成字符串
*/
@Test
public void testObjectToJson(){
String userJson = JsonMapper.objectToJson(user);
log.info(userJson);
}
/**
* 将对象转换成格式化的字符串
*/
@Test
public void testObjectToJsonPretty(){
String userJson = JsonMapper.objectToJsonPretty(user);
log.info(userJson);
}
}
Json转换成对象
package com.lyc.demo;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Before;
import org.junit.Test;
@Slf4j
public class JsonToObjectTest {
private String json;
/**
* 准备json数据
*/
@Before
public void testBofore(){
//初始化User对象
User user = User.builder()
.id(1)
.name("zhangsan")
.build();
//将对象转化成字符串
json = JsonMapper.objectToJson(user);
}
/**
* 将json转换成对象User(TypeReference)
*/
@Test
public void jsonToObjectTypeReference(){
//将json字符串转换成User对象
User user = JsonMapper.jsonToObject(json, new TypeReference<User>(){});
//如果转换不为空
if(user != null){
log.info("user.id = " + user.getId() + "," + "user.name = " + user.getName());
} else {
log.error("Json转换对象失败!");
}
}
/**
* 将json转换成对象User(Class)
*/
@Test
public void jsonToObjectByClass(){
//将json字符串转换成User对象
User user = JsonMapper.jsonToObject(json, User.class);
//如果转换不为空
if(user != null){
log.info("user.id = " + user.getId() + "," + "user.name = " + user.getName());
} else {
log.error("Json转换对象失败!");
}
}
}
Json与List对象互转
package com.lyc.demo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
@Slf4j
public class JsonToList {
private String json;
/**
* 将list对象转换成json
*/
@Before
public void testListToJson(){
User user1 = User.builder()
.id(1)
.name("zhangsan")
.build();
User user2 = User.builder()
.id(2)
.name("lisi")
.build();
List<User> list = Lists.newArrayList();
list.add(user1);
list.add(user2);
json = JsonMapper.objectToJson(list);
}
/**
* 将json转换成list对象(TypeReference)
*/
@Test
public void testJsonToListTypeReference(){
List<User> list = JsonMapper.jsonToObject(json, new TypeReference<List<User>>() {
});
if(list != null){
User user1 = list.get(0);
User user2 = list.get(1);
log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
}
}
/**
* 将json转换成list对象
*/
@Test
public void testJsonToListClass(){
List<User> list = JsonMapper.jsonToObject(json, List.class,User.class);
if(list != null){
User user1 = list.get(0);
User user2 = list.get(1);
log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
}
}
}
Json与Map对象互转
package com.lyc.demo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
@Slf4j
public class JsonToMap {
private String json;
/**
* 将map对象转换成json
*/
@Before
public void testMapToJson(){
User user1 = User.builder()
.id(1)
.name("zhangsan")
.build();
User user2 = User.builder()
.id(2)
.name("lisi")
.build();
Map<String,User> map = Maps.newHashMap();
map.put("user1",user1);
map.put("user2",user2);
json = JsonMapper.objectToJson(map);
}
/**
* 将json转换成map对象(TypeReference)
*/
@Test
public void testJsonToMapTypeReference(){
Map<String,User> map = JsonMapper.jsonToObject(json, new TypeReference<Map<String,User>>() {
});
if(map != null){
User user1 = map.get("user1");
User user2 = map.get("user2");
log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
}
}
/**
* 将json转换成mao对象(Class)
*/
@Test
public void testJsonToMapClass(){
Map<String,User> map = JsonMapper.jsonToObject(json, Map.class,String.class,User.class);
if(map != null){
User user1 = map.get("user1");
User user2 = map.get("user2");
log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
}
}
}
Json与对象在转换中遇到空属性
package com.lyc.demo;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Before;
import org.junit.Test;
@Slf4j
public class JsonToStudentTest {
private String json;
/**
* 将student对象转换成json()
*/
@Before
public void testStudentToJson(){
Student student = Student.builder()
.id(1)
.name("zhangsan")
.age(null)
.build();
json = JsonMapper.objectToJson(student);
log.info("转换成的student的json信息如下:");
log.info(json);
}
/**
* 将json转换成student(TypeReference)
*/
@Test
public void testJsonToStudentTypeReference(){
Student student = JsonMapper.jsonToObject(json, new TypeReference<Student>() {
});
log.info("student.id = " + student.getId() + ",student.name = " + student.getName() +
",student.age = " + student.getAge() + ",student.no = " + student.getNo());
}
/**
* 将json转换成student(Class)
*/
@Test
public void testJsonToStudentClass(){
Student student = JsonMapper.jsonToObject(json, Student.class);
log.info("student.id = " + student.getId() + ",student.name = " + student.getName() +
",student.age = " + student.getAge() + ",student.no = " + student.getNo());
}
}