Heim > Fragen und Antworten > Hauptteil
So stringen Sie JSON wie folgt:
{
"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}]
}
Konvertieren in: Map<String, List<Unit>>
Sie können Jackson, FastJson, Jsoblib verwenden,
Bitte geben Sie mir ein paar Ratschläge!
过去多啦不再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;
}
扔个三星炸死你2017-07-05 10:04:17
哈哈,看来已经来晚了啊...题主已经采纳答案了嘛,不过lamdba
的方式还是要强烈安利给题主哈,因为代码简单的很多(用的fastjson
哈,不过其他应该也差不多)
思路就是,题主的json
字符串其实总得来说就是一个key-value
的形式,应该是满足了最终题主想要的Map<String, List<Unit>>
的结构了,所以直接一个Collectors.toMap
就搞定啦
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)));
然后...就完了噻...就这么点代码...(s
就是你那个json
字符串哈)