ObjectMapper工具类 json字符串和 对象之间转换。和对于 ObjectMapper的一些可选设置。
添加maven 依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency>
点击查看代码
package com.itheima.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import lombok.Builder;
import java.text.SimpleDateFormat;
public class JsonMapperUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
//config
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);//设置在反序列化时忽略在JSON字符串中存在,而在Java中不存在的属性
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);//如果是空对象的时候,不抛异常
objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);//属性为null的转换
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
/**
* 对象转String
* @param src
* @param <T>
* @return
*/
public static <T> String obj2String(T src){
if (null == src){
return null;
}
try {
return src instanceof String ? (String) src:objectMapper.writeValueAsString(src);
} catch (Exception e) {
return null;
}
}
public static <T> T string2Obj(String src, TypeReference<T> typeReference){
if(null == src || null == typeReference){
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
} catch (Exception e){
return null;
}
}
public static void main(String[] args) {
SysAcl acl = SysAcl.builder().id(1).name("测试").remark("ceshi").build();
String a = JsonMapperUtil.obj2String(acl);
System.out.println(a);
SysAcl sysAcl = JsonMapperUtil.string2Obj(a, new TypeReference<SysAcl>() {});
System.out.println(sysAcl.toString());
}
@Builder
public class SysAcl{
private Integer id;
private String name;
private String remark;
}
}