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:43

You can convert any JSON to map by using Jackson library as below:

String json = "{\r\n\"name\" : \"abc\" ,\r\n\"email id \" : [\"abc@gmail.com\",\"def@gmail.com\",\"ghi@gmail.com\"]\r\n}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
System.out.println(map);

Maven Dependencies for Jackson :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

Hope this will help. Happy coding :)

查看更多
爱死公子算了
3楼-- · 2019-01-01 14:46

You can use Jackson API as well for this :

    final String json = "....your json...";
    final ObjectMapper mapper = new ObjectMapper();
    final MapType type = mapper.getTypeFactory().constructMapType(
        Map.class, String.class, Object.class);
    final Map<String, Object> data = mapper.readValue(json, type);
查看更多
残风、尘缘若梦
4楼-- · 2019-01-01 14:46

If you hate recursion - using a Stack and javax.json to convert a Json String into a List of Maps:

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.json.Json;
import javax.json.stream.JsonParser;

public class TestCreateObjFromJson {
    public static List<Map<String,Object>> extract(InputStream is) {
        List extracted = new ArrayList<>();
        JsonParser parser = Json.createParser(is);

        String nextKey = "";
        Object nextval = "";
        Stack s = new Stack<>();
        while(parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch(event) {
                case START_ARRAY :  List nextList = new ArrayList<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextList);
                                    }
                                    s.push(nextList);
                                    break;
                case START_OBJECT : Map<String,Object> nextMap = new HashMap<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextMap);
                                    }
                                    s.push(nextMap);
                                    break;
                case KEY_NAME : nextKey = parser.getString();
                                break;
                case VALUE_STRING : setValue(s,nextKey,parser.getString());
                                    break;
                case VALUE_NUMBER : setValue(s,nextKey,parser.getLong());
                                    break;
                case VALUE_TRUE :   setValue(s,nextKey,true);
                                    break;
                case VALUE_FALSE :  setValue(s,nextKey,false);
                                    break;
                case VALUE_NULL :   setValue(s,nextKey,"");
                                    break;
                case END_OBJECT :   
                case END_ARRAY  :   if(s.size() > 1) {
                                        // If this is not a root object, move up
                                        s.pop(); 
                                    } else {
                                        // If this is a root object, add ir ro rhw final 
                                        extracted.add(s.pop()); 
                                    }
                default         :   break;
            }
        }

        return extracted;
    }

    private static void setValue(Stack s, String nextKey, Object v) {
        if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v);
        else ((List)s.peek()).add(v);
    }
}
查看更多
刘海飞了
5楼-- · 2019-01-01 14:49

Here is Vikas's code ported to JSR 353:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;

public class JsonUtils {
    public static Map<String, Object> jsonToMap(JsonObject json) {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JsonObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }

    public static Map<String, Object> toMap(JsonObject object) throws JsonException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keySet().iterator();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object 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);
        }
        return map;
    }

    public static List<Object> toList(JsonArray array) {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.size(); i++) {
            Object value = array.get(i);
            if(value instanceof JsonArray) {
                value = toList((JsonArray) value);
            }

            else if(value instanceof JsonObject) {
                value = toMap((JsonObject) value);
            }
            list.add(value);
        }
        return list;
    }
}
查看更多
公子世无双
6楼-- · 2019-01-01 14:51

I wrote this code some days back by recursion.

public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
    Map<String, Object> retMap = new HashMap<String, Object>();

    if(json != JSONObject.NULL) {
        retMap = toMap(json);
    }
    return retMap;
}

public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<String, Object>();

    Iterator<String> keysItr = object.keys();
    while(keysItr.hasNext()) {
        String key = keysItr.next();
        Object 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);
    }
    return map;
}

public static List<Object> toList(JSONArray array) throws JSONException {
    List<Object> list = new ArrayList<Object>();
    for(int i = 0; i < array.length(); i++) {
        Object value = array.get(i);
        if(value instanceof JSONArray) {
            value = toList((JSONArray) value);
        }

        else if(value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }
        list.add(value);
    }
    return list;
}
查看更多
浪荡孟婆
7楼-- · 2019-01-01 14:52

Using GSon, you can do the following:

Map<String, Object> retMap = new Gson().fromJson(
    jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
查看更多
登录 后发表回答