public static List<Map<String, String>> getPropertiesFromJson(String json) { List<Map<String, String>> properties = null; json = json.trim(); if (json.startsWith("{")) { properties = new ArrayList<Map<String, String>>(); properties.add(processJsonMap(json)); } else if (json.startsWith("[")) { try { properties = processJsonArray(new JSONArray(json)); } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } else { throw new RuntimeException("The JSON string must start with { or ["); // i18n } return properties; }
private static Map processJsonObject(JSONObject jo) { Map<String, Object> map = new HashMap<String, Object>(); try { Iterator i = jo.keys(); while (i.hasNext()) { String key = (String)i.next(); Object value = jo.get(key); if (value instanceof JSONArray) { map.put(key, processJsonArray((JSONArray)value)); } else if (value instanceof JSONObject) { map.put(key, processJsonObject((JSONObject)value)); } else if (value.getClass().getSimpleName().equalsIgnoreCase("null")) { // The Map may not store null values, but we shouldn't rely on // that behavior, just to be safe map.put(key, null); } else { map.put(key, value); } } } catch (JSONException e) { LogHelper.log(RestClientLogging.logger, Level.SEVERE, RestClientLogging.REST_CLIENT_JSON_ERROR, e); } return map; }
private static List processJsonArray(JSONArray ja) { List results = new ArrayList(); try { for (int i = 0; i < ja.length(); i++) { Object entry = ja.get(i); if (entry instanceof JSONArray) { results.add(processJsonArray((JSONArray)entry)); } else if (entry instanceof JSONObject) { results.add(processJsonObject((JSONObject)entry)); } else { results.add(entry); } } } catch (JSONException e) { LogHelper.log(RestClientLogging.logger, Level.SEVERE, RestClientLogging.REST_CLIENT_JSON_ERROR, e); } return results; }