cari

Rumah  >  Soal Jawab  >  teks badan

java - Tukar rentetan json ke Map<String, List<Object>>, bagaimana untuk beroperasi?

Cara rentetan json seperti berikut:
{
"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}]
}
Tukar kepada: Map<String, List<Unit>> Anda boleh menggunakan jackson, fastjson, jsoblib,
Sila berikan saya nasihat!

巴扎黑巴扎黑2724 hari yang lalu1570

membalas semua(2)saya akan balas

  • 过去多啦不再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;
    }

    balas
    0
  • 扔个三星炸死你

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

    Haha, nampaknya dah terlambat... Penyoal sudah terima jawapannya, tapi lamdba的方式还是要强烈安利给题主哈,因为代码简单的很多(用的fastjsonha, tapi yang lain sepatutnya serupa)

    Ideanya, topik json字符串其实总得来说就是一个key-value的形式,应该是满足了最终题主想要的Map<String, List<Unit>>的结构了,所以直接一个Collectors.toMap sudah selesai

    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...tu je...sikit kod...(s就是你那个jsonstring haha)

    balas
    0
  • Batalbalas