将json串如下:
{
"1":[{"id":001,"age":20,"type":2,"code":"101","password":123456}, {"id":002,"age":22,"type":1,"code":"102","password":123456}],
"2":[{"id":003,"age":23,"type":1,"code":"103","password":123456}]
}
转换为:Map<String, List<User>> 类型
1. 思路就是,json
字符串其实总得来说就是一个key-value
的形式,应该是满足了最终想要的Map<String, List<Unit>>
的结构了,所以直接一个Collectors.toMap
就搞定啦
Map<String, List<User>> result = JSONObject.parseObject(s)
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> JSONObject.parseArray(String.valueOf(entry.getValue()), User.class)));
2. 自己封装一个将 json 解析为常用数据类型的工具类
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}