Jackson实现Java对象与JSON的相互转换

一、POJOtoString

    @Test
    public  void toStr(){
        TObj one=new TObj();
        one.setKey("myKey");
        one.setValue(3330L);
        ObjectMapper mapper = new ObjectMapper();
        try {
            //单个java对象序列化为String
            String jsonStr=mapper.writeValueAsString(one);
            System.out.println("jsonStr--> "+jsonStr);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        
        List objs=new ArrayList();
        objs.add(one);
        TObj two=new TObj();
        two.setKey("myKey2");
        two.setValue(3331L);
        objs.add(two);
        try {
            //集合序列化为String
            String jsonStrs=mapper.writeValueAsString(objs);
            System.out.println("jsonStrs--> "+jsonStrs);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

output:

jsonStr--> {"key":"myKey","value":3330}

jsonStrs--> [{"key":"myKey","value":3330},{"key":"myKey2","value":3331}]


二、StringToObj

    @Test
    public void toObj(){
        String oneStr="{\"key\":\"myKey\",\"value\":3330}";
        String objsStr="[{\"key\":\"myKey\",\"value\":3330},{\"key\":\"myKey2\",\"value\":3331}]";
        ObjectMapper mapper = new ObjectMapper();
        try {
            //单对象反序列化
            TObj one=mapper.readValue(oneStr,TObj.class);
            System.out.println(one);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            //反序列化为集合
            List objs=mapper.readValue(objsStr,List.class);
            /*实际会将集合中的元素解析成HashMap,如节点解析,即如同对其中的每个POJO进行了mapper.readValue(str,HashMap.class)
            */
            for(Object oo:objs){
                System.out.println(oo.getClass()); //class java.util.LinkedHashMap
                System.out.println(((LinkedHashMap)oo).get("key")); //myKey
            }
            /*可使用mapper.readValue(String var1, TypeReference var2)来解析成单个TObj对象 */
            List objs2=mapper.readValue(objsStr,new TypeReference>(){});
            for(TObj oo:objs2){
                System.out.println(oo.getClass());//class TObj
                System.out.println(oo); // key=myKey, value=3330
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
output:

key=myKey, value=3330
class java.util.LinkedHashMap
myKey
class java.util.LinkedHashMap
myKey2
class com.yy.cs.base.json.TObj
key=myKey, value=3330
class com.yy.cs.base.json.TObj
key=myKey2, value=3331

注意,集合相关的反序列化若想转成带范型的则应使用第二种方式。

以下为网上看到的较好的表达:

Jackson支持3种使用方式:
1、Data Binding:最方便使用.

(1)Full Data Binding:

private static final String MODEL_BINDING = "{\"name\":\"name1\",\"type\":1}"; 
  public void fullDataBinding() throws Exception{ 
    ObjectMapper mapper = new ObjectMapper(); 
    Model user = mapper.readValue(MODEL_BINDING, Model.class);//readValue到一个实体类中. 
    System.out.println(user.getName()); 
    System.out.println(user.getType()); 
  } 

Model类:

private static class Model{ 
    private String name; 
    private int type; 
      
    public String getName() { 
      return name; 
    } 
    public void setName(String name) { 
      this.name = name; 
    } 
    public int getType() { 
      return type; 
    } 
    public void setType(int type) { 
      this.type = type; 
    } 
  } 

(2)Raw Data Binding:

  public void rawDataBinding() throws Exception{ 
    ObjectMapper mapper = new ObjectMapper(); 
    HashMap map = mapper.readValue(MODEL_BINDING,HashMap.class);//readValue到一个原始数据类型. 
    System.out.println(map.get("name")); 
    System.out.println(map.get("type")); 
  } 

(3)generic Data Binding:

private static final String GENERIC_BINDING = "{\"key1\":{\"name\":\"name2\",\"type\":2},\"key2\":{\"name\":\"name3\",\"type\":3}}"; 
  public void genericDataBinding() throws Exception{ 
    ObjectMapper mapper = new ObjectMapper(); 
    HashMap modelMap = mapper.readValue(GENERIC_BINDING,new TypeReference>(){});//readValue到一个范型数据中. 
    Model model = modelMap.get("key2"); 
    System.out.println(model.getName()); 
    System.out.println(model.getType()); 
  } 

你可能感兴趣的:(Java)