使用場景:
一般都是從庫中查出來的json對象 / json數組 , 我們需要轉換爲map / list集合.
使用方法:
Map map = JSON.parseObject( json , Map.class)
1.對象格式: {“0”:0,“10”:0,“15”:0} )
轉換爲Map集合 -> Map<T,T>
無序轉換: ( Map.class )
// 假設庫中數據爲如下json串.
String map = "{ aaa:123456, bbb:234356, ccc:876541}";
Map<String,String> hashMap = JSON.parseObject(map , Map.class);
System.out.println("轉換後結果:"+hashMap); //{aaa=123456, ccc=876541, bbb=234356}
有序轉換: ( Map.class )
Map<String,String> hashMap = JSON.parseObject(map , LinkedHashMap.class);
System.out.println("轉換後結果:"+hashMap); //{aaa=123456, bbb=234356, ccc=876541}
2.嵌套對象格式: { aaa:{5:03, … }, bbb:{5:12, … } }
轉換爲Map集合 -> Map<T,Map<T,T>>
無序轉換: ( Map.class )
// 假設庫中數據爲如下json串.
String map = "{19:{0:0,5:0,1:0,4:0}}";
Map<Integer,Map<Integer , Integer>> beforeMap = JSON.parseObject(map , Map.class);
System.out.println(beforeMap); // 未處理結果 ---> {19={"0":0,"1":0,"4":0,"5":0}}
有序轉換: ( new TypeReference )
Map<Integer,LinkedHashMap<Integer , Integer>> afterMap = JSON.parseObject(map , new TypeReference<LinkedHashMap<Integer, LinkedHashMap<Integer, Integer>>>(){
});
System.out.println(afterMap); // 處理後結果 ---> {19={0=0, 5=0, 1=0, 4=0}}