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

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

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

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

@Test
  public void test10() throws Exception {
    //準(zhǔn)備一下數(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"]}
    // 正常反序列化,未報(bào)錯(cuò)
    Map<String, Set<String>> map01 = om.readValue(str01, Map.class);
    // 取值的時(shí)候就會(huì)報(bào)錯(cuò)了
    Set<String> aaa = map01.get("aaa");
  }

報(bào)錯(cuò):

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

報(bào)錯(cuò)信息:無(wú)法將list轉(zhuǎn)為set。

再拓展開(kāi)來(lái),其實(shí)當(dāng)你的Map里面的對(duì)象如果是object類(lèi)型的自定義類(lèi)型,其實(shí)都會(huì)報(bào)錯(cuò),無(wú)法被強(qiáng)轉(zhuǎn),那么我們就需要指定jackson反序列化為什么類(lèi)型,而不是讓它自主決定反序列化成什么類(lèi)型,需要用到TypeReference,直接上代碼。

@Test
public void test10() throws Exception {
  //準(zhǔn)備一下數(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
}

補(bǔ)充知識(shí):Jackson 處理復(fù)雜類(lèi)型(List,map)兩種方法

方法一

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

當(dāng)轉(zhuǎn)換完成時(shí)一定要用這個(gè)轉(zhuǎn)換對(duì)象,如果不用這個(gè)對(duì)象是沒(méi)有值的.如下,當(dāng)我打印時(shí)這個(gè)projects對(duì)象才有值,否則projects無(wú)值 .

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ù)雜類(lèi)型問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論