java - Comment convertir une chaîne JSON en Map<String, List<Object>>?
巴扎黑
巴扎黑 2017-07-05 10:02:17
0
2
1509

Comment chaîner json comme suit :
{
"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}]
}
Convertir en : Map<String, List<Unit>> Vous pouvez utiliser jackson, fastjson, jsoblib,
Veuillez me donner quelques conseils!

巴扎黑
巴扎黑

répondre à tous(2)
过去多啦不再A梦
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;
}
扔个三星炸死你

Haha, il semble qu'il soit trop tard... La personne qui a posé la question a déjà accepté la réponse, mais lamdba的方式还是要强烈安利给题主哈,因为代码简单的很多(用的fastjsonha, mais les autres devraient être similaires)

L'idée est que le sujet json字符串其实总得来说就是一个key-value的形式,应该是满足了最终题主想要的Map<String, List<Unit>>的结构了,所以直接一个Collectors.toMap est terminé

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

Alors...c'est tout...juste un petit peu de code...(s就是你那个jsonstring haha)

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!