直接上代码,实现了对嵌套的对象进行转换。
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; }
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/172463.html原文链接:https://javaforall.cn