jackson的应用

直接上代码

  1 package com.demo.jackson.utils;
  2 
  3 import com.fasterxml.jackson.core.JsonProcessingException;
  4 import com.fasterxml.jackson.core.type.TypeReference;
  5 import com.fasterxml.jackson.databind.DeserializationFeature;
  6 import com.fasterxml.jackson.databind.JavaType;
  7 import com.fasterxml.jackson.databind.ObjectMapper;
  8 import lombok.extern.slf4j.Slf4j;
  9 import org.springframework.util.StringUtils;
 10 
 11 @Slf4j
 12 public class JsonUtil {
 13     private static ObjectMapper objectMapper = new ObjectMapper();
 14     static {
 15         //忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
 16         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 17     }
 18 
 19     /**
 20      * 对象转换成Sting
 21      * @param obj
 22      * @param <T>
 23      * @return
 24      */
 25     public static <T> String obj2String(T obj){
 26         if (obj == null) {
 27             return null;
 28         }
 29         try {
 30             return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
 31         } catch (JsonProcessingException e) {
 32             System.out.println("Parse Object to String error");
 33             e.printStackTrace();
 34             return null;
 35         }
 36     }
 37     /**
 38      * 规范地将对象转换成Sting
 39      * @param obj
 40      * @param <T>
 41      * @return
 42      */
 43     public static <T> String obj2StringPretty(T obj){
 44         if(obj == null){
 45             return null;
 46         }
 47         try {
 48             return obj instanceof String ? (String)obj :  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
 49         } catch (Exception e) {
 50             log.warn("Parse Object to String error",e);
 51             return null;
 52         }
 53     }
 54 
 55     /**
 56      * String转换成obj对象
 57      * @param str
 58      * @param clazz
 59      * @param <T>
 60      * @return
 61      */
 62     public  static <T> T str2Obj(String str, Class<T> clazz){
 63         if(str==null){
 64             return null;
 65         }
 66         try {
 67             return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
 68         } catch (Exception e) {
 69             e.printStackTrace();
 70             return null;
 71         }
 72     }
 73 
 74     /**
 75      * String转换成对象
 76      * @param str
 77      * @param typeReference
 78      * @param <T>
 79      * @return
 80      */
 81     public static <T> T string2Obj(String str, TypeReference<T> typeReference){
 82         if(StringUtils.isEmpty(str) || typeReference == null){
 83             return null;
 84         }
 85         try {
 86             return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
 87         } catch (Exception e) {
 88             log.warn("Parse String to Object error",e);
 89             return null;
 90         }
 91     }
 92 
 93     /**
 94      * String转换成对象
 95      * @param str
 96      * @param collectionClass
 97      * @param elementClasses
 98      * @param <T>
 99      * @return
100      */
101     public static <T> T string2Obj(String str, Class<?> collectionClass, Class<?>... elementClasses){
102         JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
103         try {
104             return objectMapper.readValue(str,javaType);
105         } catch (Exception e) {
106             log.warn("Parse String to Object error",e);
107             return null;
108         }
109     }
110 }

测试:

  1 package com.demo.jackson.test;
  2 
  3 import com.demo.jackson.entity.Student;
  4 import com.demo.jackson.utils.JsonUtil;
  5 import com.fasterxml.jackson.core.type.TypeReference;
  6 import com.fasterxml.jackson.databind.JsonNode;
  7 import com.fasterxml.jackson.databind.ObjectMapper;
  8 import org.junit.Test;
  9 
 10 import java.util.*;
 11 
 12 @SuppressWarnings("ALL")
 13 public class JacksonTest {
 14     /**
 15      * 序列化
 16      */
 17     @Test
 18     public void test01(){
 19         Student s = new Student();
 20         s.setName("cjj");
 21         s.setAge(22);
 22         s.setProfileImageUrl("link");
 23         String s1 = JsonUtil.obj2String(s);
 24         System.out.println(s1);
 25 
 26         Map<String, List<Integer>> map = new HashMap<>();
 27         map.put("a", Arrays.asList(1, 2, 3));
 28         map.put("b", Arrays.asList(1, 2, 3));
 29         String result1 = JsonUtil.obj2StringPretty(map);
 30         System.out.println(result1);
 31     }
 32 
 33     /**
 34      * 反序列化
 35      */
 36     @Test
 37     public void Test02(){
 38         String str = "{\"name\":\"name\",\"age\":10,\"profileImageUrl\":\"link\"}";
 39         Student student = JsonUtil.str2Obj(str, Student.class);
 40         System.out.println(student);
 41     }
 42     @Test
 43     public void test03() throws Exception {
 44 
 45         Student student1 = new Student();
 46         student1.setAge(10);
 47         student1.setName("name1");
 48         student1.setProfileImageUrl("link1");
 49 
 50         Student student2 = new Student();
 51         student2.setAge(20);
 52         student2.setName("name2");
 53         student2.setProfileImageUrl("link2");
 54 
 55         List<Student> studentList = new ArrayList<>();
 56         studentList.add(student1);
 57         studentList.add(student2);
 58         String result = JsonUtil.obj2String(studentList);
 59         // [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
 60         System.out.println(result);
 61 
 62         List<Student> finalList = JsonUtil.string2Obj(result, new TypeReference<List<Student>>() {});
 63         // [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
 64         System.out.println(finalList);
 65     }
 66     @Test
 67     public void test04() throws Exception {
 68 
 69         Student student1 = new Student();
 70         student1.setAge(10);
 71         student1.setName("name1");
 72         student1.setProfileImageUrl("link1");
 73 
 74         Student student2 = new Student();
 75         student2.setAge(20);
 76         student2.setName("name2");
 77         student2.setProfileImageUrl("link2");
 78 
 79         List<Student> studentList = new ArrayList<>();
 80         studentList.add(student1);
 81         studentList.add(student2);
 82         String result = JsonUtil.obj2String(studentList);
 83         // [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
 84         System.out.println(result);
 85 
 86         List<Student> finalList = JsonUtil.string2Obj(result, List.class, Student.class);
 87         // [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
 88         System.out.println(finalList);
 89     }
 90     @Test
 91     public void jsonProperty() throws Exception {
 92 
 93         String str = "{\"name\":\"name\",\"age\":10,\"setImage\":\"link\"}";
 94         Student student1 = JsonUtil.string2Obj(str, Student.class);
 95         // name
 96         System.out.println(student1.getName());
 97         // 10
 98         System.out.println(student1.getAge());
 99         // link
100         System.out.println(student1.getProfileImageUrl());
101         // {"name":"name","age":10,"getImage":"link"}
102         System.out.println(JsonUtil.obj2String(student1));
103     }
104 
105     /**
106      * 除了将json转为对象外,还可以用Tree Mode方式解析JSON,全程无脑操作,
107      * 除了一些特别复杂的JSON,或者只取JSON中的一部分,千万不要用这种二B方式解析JSON。
108      * 正确的方式是将JSON直接转为对象。
109      * @throws Exception
110      */
111     @Test
112     public void parseJson() throws Exception {
113         String jsonStr = "{\"name\":\"zhansan\",\"age\":100,\"schools\":[{\"name\":\"tsinghua\",\"location\":\"beijing\"},{\"name\":\"pku\",\"location\":\"beijing\"}]}";
114 
115         ObjectMapper objectMapper = new ObjectMapper();
116         JsonNode jsonNode = objectMapper.readTree(jsonStr);
117 
118         String name = jsonNode.get("name").asText();
119         int age = jsonNode.get("age").asInt();
120         // name is zhansan age is 100
121         System.out.println("name is " + name + " age is " + age);
122 
123         JsonNode schoolsNode = jsonNode.get("schools");
124         for (int i = 0; i < schoolsNode.size(); i++) {
125             String schooleName = schoolsNode.get(i).get("name").asText();
126             String schooleLocation = schoolsNode.get(i).get("location").asText();
127             // schooleName is tsinghua schooleLocation is beijing
128             // schooleName is pku schooleLocation is beijing
129             System.out.println("schooleName is " + schooleName + " schooleLocation is " + schooleLocation);
130         }
131     }
132 }

 

posted @ 2019-05-17 10:43  littlecarzz  阅读(430)  评论(0编辑  收藏  举报