欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決Jackson反序列化map,set等復(fù)雜類型問題

 更新時間:2020年09月28日 09:30:27   作者:MrHamster  
這篇文章主要介紹了解決Jackson反序列化map,set等復(fù)雜類型問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

工作中遇到了這個問題,我簡單的用代碼復(fù)現(xiàn)一下,就是一個map,value又為一個set,導致反序列化報錯

@Test
  public void test10() throws Exception {
    //準備一下數(shù)據(jù)
    Map<String, Set<String>> map = new HashMap<>();
    map.put("aaa",new HashSet<String>(){{add("111");add("222");}});
    ObjectMapper om = new ObjectMapper();
    String str01 = om.writeValueAsString(map);
    //System.out.println(str01); // {"aaa":["111","222"]}
    // 正常反序列化,未報錯
    Map<String, Set<String>> map01 = om.readValue(str01, Map.class);
    // 取值的時候就會報錯了
    Set<String> aaa = map01.get("aaa");
  }

報錯:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Set

報錯信息:無法將list轉(zhuǎn)為set。

再拓展開來,其實當你的Map里面的對象如果是object類型的自定義類型,其實都會報錯,無法被強轉(zhuǎn),那么我們就需要指定jackson反序列化為什么類型,而不是讓它自主決定反序列化成什么類型,需要用到TypeReference,直接上代碼。

@Test
public void test10() throws Exception {
  //準備一下數(shù)據(jù)
  Map<String, Set<String>> map = new HashMap<>();
  map.put("aaa",new HashSet<String>(){{add("111");add("222");}});
  ObjectMapper om = new ObjectMapper();
  String str01 = om.writeValueAsString(map);
  //System.out.println(str01); // {"aaa":["111","222"]}
  Map<String, Set<String>> m = om.readValue(str01, new TypeReference<HashMap<String, Set<String>>>() {});
  Set<String> aaa = m.get("aaa");
  System.out.println(aaa instanceof HashSet); // true
}

補充知識:Jackson 處理復(fù)雜類型(List,map)兩種方法

方法一

String jsonString="[{'id':'1'},{'id':'2'}]"; 
ObjectMapper mapper = new ObjectMapper(); 
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Bean.class); 
//如果是Map類型 mapper.getTypeFactory().constructParametricType(HashMap.class,String.class, Bean.class); 
List<Bean> lst = (List<Bean>)mapper.readValue(jsonString, javaType);  

當轉(zhuǎn)換完成時一定要用這個轉(zhuǎn)換對象,如果不用這個對象是沒有值的.如下,當我打印時這個projects對象才有值,否則projects無值 .

List<AlertProjectInfo> projects = mapper.readValue(subProject, mapper.getTypeFactory().constructCollectionType(List.class, AlertProjectInfo.class));
System.out.println(projects.size());

方法二

String jsonString="[{'id':'1'},{'id':'2'}]"; 
ObjectMapper mapper = new ObjectMapper(); 
List<Bean> beanList = mapper.readValue(jsonString, new TypeReference<List<Bean>>() {}); 

以上這篇解決Jackson反序列化map,set等復(fù)雜類型問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論