java - Convert json string to Map<String, List<Object>>, how to operate?
巴扎黑
巴扎黑 2017-07-05 10:02:17
0
2
1390

How to string json as follows:
{
"1":[{"id":6397891,"rate":81,"type":2,"unitId":1,"userId": 7133}, {"id":6397882,"rate":72,"type":1,"unitId":1,"userId":7133}],
"2":[{"id":6397906 ,"rate":90,"type":1,"unitId":2,"userId":7133}]
}
Convert to: Map<String, List<Unit>> Type
You can use jackson, fastjson, or jsoblib.
Please give me some advice!

巴扎黑
巴扎黑

reply all(2)
过去多啦不再A梦
public static Map jsonToMap(JSONObject json) throws JSONException {
    Map retMap = new HashMap();

    if(json != JSONObject.NULL) {
        retMap = toMap(json);
    }
    return retMap;
}

public static Map toMap(JSONObject object) throws JSONException {
    Map map = new HashMap();

    Iterator 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 toList(JSONArray array) throws JSONException {
    List list = new ArrayList();
    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;
}

                            
                                                            
                            
                            
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!