ObjectMapper的用法 工具类
首先在pom.xml引入
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.3</version> </dependency>
定义JsonMapper工具类
- public class JsonMapper {
-
- private static ObjectMapper objectMapper = new ObjectMapper();
-
- static {
- //config
- objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);//设置在反序列化时忽略在JSON字符串中存在,而在Java中不存在的属性
- objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);//如果是空对象的时候,不抛异常
- objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
- objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.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 = JsonMapper.obj2String(acl);
- System.out.println(a);
- SysAcl sysAcl = JsonMapper.string2Obj(a, new TypeReference<SysAcl>() {});
- System.out.println(sysAcl.toString());
- }