How JSON string into a collection Map and disorderly solve the problem? (Including nested map solution)

Usage scenarios:
               usually check out from the library objects json / json array, we need to be converted to map / list collection.

Usage:
               the Map Map = JSON.parseObject (JSON, Map.class)

 

1. Object Format: { "0": 0, "10": 0, "15": 0})

Is converted to a set of Map -> Map <T, T>

Conversion disorder: (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}

Ordered conversion: (Map.class)

Map<String,String> hashMap = JSON.parseObject(map , LinkedHashMap.class);
System.out.println("转换后结果:"+hashMap);   //{aaa=123456, bbb=234356, ccc=876541}

2. nested object format: {aaa: {5:03, ...}, bbb: {5:12, ...}}

Is converted to a set of Map -> Map <T, Map <T, T >>

Conversion disorder: (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}}

Ordered conversion: (new 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}}
Published 107 original articles · won praise 173 · views 120 000 +

Guess you like

Origin blog.csdn.net/qq_42986107/article/details/89684787