1

There are quite a few questions raised to convert json to HashMap. I hope it helps everybody.

The following code will convert the direct values or Array of values, into a HashMap.

1 Answer 1

1

// Function called recursively

 private static Map getMap(JSONObject object, String json) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Object jsonObject = null;

        Iterator<String> keys = object.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            Object value = object.get(key);

            if (value instanceof JSONObject) {
                map.put(key, getMap((JSONObject) value, json));
                continue;
            }

         // If value is in the form of array

            if (value instanceof JSONArray) {
                JSONArray array = ((JSONArray) value);
                List list = new ArrayList();
                for (int i = 0 ; i < array.length() ; i++) {
                    jsonObject = array.get(i);
                    if (jsonObject instanceof JSONObject) {
                        list.add(getMap((JSONObject) jsonObject, json));
                    } else {
                        list.add(jsonObject);

                    }
                }
                map.put(key, list);
                continue;
            }

            map.put(key, value);
        }
        return map;
    }

// Calling Method

public static Map<String, Object> convertJsonToMap(String json) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject jsonObject = null;

        try {
            if (null != json) {
                jsonObject = new JSONObject(json);
                map = getMap(jsonObject, json);
            }

        } catch (Exception e) {
            throw new SystemException("Unable to read JSOn Object");
            // TODO : Handle Exception
        }
        return map;
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.