1. 程式人生 > >JSONObject轉Map的實現

JSONObject轉Map的實現

直接上程式碼,實現了對巢狀的物件進行轉換。

private Map<String, Object> toMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Object value;
String key;
for (Iterator<?> it = object.keys(); it.hasNext() ; ) {
key = (String) it.next();
if (object.isNull(key)) {
map.put(key, null);
} else {
try {
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);
} catch (JSONException e) {
logger.debug(e.getMessage(), e);
}
}
}
return map;
}

private List toList(JSONArray array) {
List list = new ArrayList();
Object value;
for (int i = 0; i < array.length(); i++) {
try {
value = array.get(i);
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
} catch (JSONException e) {
logger.debug(e.getMessage(), e);
}
}
return list;
}