Convert a JSON String to a HashMap

2019-01-01 14:20发布

I'm using Java, and I have a String which is JSON:

{
"name" : "abc" ,
"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]
}

Then my Map in Java:

Map<String, Object> retMap = new HashMap<String, Object>();

I want to store all the data from the JSONObject in that HashMap.

Can anyone provide code for this? I want to use the org.json library.

16条回答
何处买醉
2楼-- · 2019-01-01 14:59

try this code :

 Map<String, String> params = new HashMap<String, String>();
                try
                {

                   Iterator<?> keys = jsonObject.keys();

                    while (keys.hasNext())
                    {
                        String key = (String) keys.next();
                        String value = jsonObject.getString(key);
                        params.put(key, value);

                    }


                }
                catch (Exception xx)
                {
                    xx.toString();
                }
查看更多
步步皆殇っ
3楼-- · 2019-01-01 15:03

Converting a JSON String to Map

public static Map<String, Object> jsonString2Map( String jsonString ) throws JSONException{
        Map<String, Object> keys = new HashMap<String, Object>(); 

        org.json.JSONObject jsonObject = new org.json.JSONObject( jsonString ); // HashMap
        Iterator<?> keyset = jsonObject.keys(); // HM

        while (keyset.hasNext()) {
            String key =  (String) keyset.next();
            Object value = jsonObject.get(key);
            System.out.print("\n Key : "+key);
            if ( value instanceof org.json.JSONObject ) {
                System.out.println("Incomin value is of JSONObject : ");
                keys.put( key, jsonString2Map( value.toString() ));
            }else if ( value instanceof org.json.JSONArray) {
                org.json.JSONArray jsonArray = jsonObject.getJSONArray(key);
                //JSONArray jsonArray = new JSONArray(value.toString());
                keys.put( key, jsonArray2List( jsonArray ));
            } else {
                keyNode( value);
                keys.put( key, value );
            }
        }
        return keys;
    }

Converting JSON Array to List

public static List<Object> jsonArray2List( JSONArray arrayOFKeys ) throws JSONException{
        System.out.println("Incoming value is of JSONArray : =========");
        List<Object> array2List = new ArrayList<Object>();
        for ( int i = 0; i < arrayOFKeys.length(); i++ )  {
            if ( arrayOFKeys.opt(i) instanceof JSONObject ) {
                Map<String, Object> subObj2Map = jsonString2Map(arrayOFKeys.opt(i).toString());
                array2List.add(subObj2Map);
            }else if ( arrayOFKeys.opt(i) instanceof JSONArray ) {
                List<Object> subarray2List = jsonArray2List((JSONArray) arrayOFKeys.opt(i));
                array2List.add(subarray2List);
            }else {
                keyNode( arrayOFKeys.opt(i) );
                array2List.add( arrayOFKeys.opt(i) );
            }
        }
        return array2List;      
    }

Display JSON of Any Format

public static void displayJSONMAP( Map<String, Object> allKeys ) throws Exception{
        Set<String> keyset = allKeys.keySet(); // HM$keyset
        if (! keyset.isEmpty()) {
            Iterator<String> keys = keyset.iterator(); // HM$keysIterator
            while (keys.hasNext()) {
                String key = keys.next();
                Object value = allKeys.get( key );
                if ( value instanceof Map ) {
                    System.out.println("\n Object Key : "+key);
                        displayJSONMAP(jsonString2Map(value.toString()));                   
                }else if ( value instanceof List ) {
                    System.out.println("\n Array Key : "+key);
                    JSONArray jsonArray = new JSONArray(value.toString());
                    jsonArray2List(jsonArray);
                }else {
                    System.out.println("key : "+key+" value : "+value);
                }
            }
        }   

    }

Google.gson to HashMap.

查看更多
萌妹纸的霸气范
4楼-- · 2019-01-01 15:08

Hope this will work, try this:

import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);

str, your JSON String

As Simple as this, if you want emailid,

String emailIds = response.get("email id").toString();
查看更多
裙下三千臣
5楼-- · 2019-01-01 15:09

Brief and Useful:

/**
 * @param jsonThing can be a <code>JsonObject</code>, a <code>JsonArray</code>,
 *                     a <code>Boolean</code>, a <code>Number</code>,
 *                     a <code>null</code> or a <code>JSONObject.NULL</code>.
 * @return <i>Appropriate Java Object</i>, that may be a <code>Map</code>, a <code>List</code>,
 * a <code>Boolean</code>, a <code>Number</code> or a <code>null</code>.
 */
public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException {
    if (jsonThing instanceof JSONArray) {
        final ArrayList<Object> list = new ArrayList<>();

        final JSONArray jsonArray = (JSONArray) jsonThing;
        final int l = jsonArray.length();
        for (int i = 0; i < l; ++i) list.add(jsonThingToAppropriateJavaObject(jsonArray.get(i)));
        return list;
    }

    if (jsonThing instanceof JSONObject) {
        final HashMap<String, Object> map = new HashMap<>();

        final Iterator<String> keysItr = ((JSONObject) jsonThing).keys();
        while (keysItr.hasNext()) {
            final String key = keysItr.next();
            map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key)));
        }
        return map;
    }

    if (JSONObject.NULL.equals(jsonThing)) return null;

    return jsonThing;
}

Thank @Vikas Gupta.

查看更多
登录 后发表回答