search

Home  >  Q&A  >  body text

java - Convert json string to Map<String, List<Object>>, how to operate?

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!

巴扎黑巴扎黑2688 days ago1534

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-07-05 10:04:17

    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;
    }

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-07-05 10:04:17

    Haha, it seems it’s too late... The questioner has already accepted the answer, but the lamdba method still needs to be strongly favored by the questioner, because the code is much simpler (using fastjsonha, but Others should be similar)

    The idea is that the json string of the question subject is actually in the form of a key-value, which should be the structure that satisfies the final question subject's desired Map<String, List<Unit>> , so just use Collectors.toMap and you’re done

    Map<String, List<Unit>> result = JSONObject.parseObject(s)
                                               .entrySet().stream()
                                               .collect(Collectors.toMap(Map.Entry::getKey, entry -> JSONObject.parseArray(String.valueOf(entry.getValue()), Unit.class)));

    Then...that's it...just this little code...(sis your jsonstring)

    reply
    0
  • Cancelreply