将JSON字符串转换为HashMap

时间:2014-02-12 06:55:03

标签: java json dictionary

我正在使用Java,我有一个JSON的字符串:

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

然后我在Java中的地图:

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

我想将JSONObject中的所有数据存储在该HashMap中。

任何人都可以为此提供代码吗?我想使用org.json库。

18 个答案:

答案 0 :(得分:197)

几天前我通过递归编写了这段代码。

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;
}

答案 1 :(得分:107)

使用GSon,您可以执行以下操作:

Map<String, Object> retMap = new Gson().fromJson(
    jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);

答案 2 :(得分:23)

希望这会奏效,试试这个:

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

str,你的JSON字符串

如此简单,如果你想要emailid,

String emailIds = response.get("email id").toString();

答案 3 :(得分:6)

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

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;


public class JsonUtils {

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

        if(json != null) {
            retMap = toMap(json);
        }
        return retMap;
    }

    public static Map<String, Object> toMap(JSONObject object) {
        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;
    }
}

答案 4 :(得分:4)

这是Vikas的代码移植到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;
    }
}

答案 5 :(得分:4)

试试这段代码:

 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();
                }

答案 6 :(得分:4)

我刚用过Gson

HashMap<String, Object> map = new Gson().fromJson(json.toString(), HashMap.class);

答案 7 :(得分:2)

您也可以使用Jackson API:

    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);

答案 8 :(得分:2)

您可以使用 Jackson 库将JSON转换为map,如下所示:

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);

Jackson 的Maven依赖关系:

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

希望这会有所帮助。快乐的编码:)

答案 9 :(得分:2)

您可以使用google gson库转换json对象。

https://code.google.com/p/google-gson/

其他像杰克逊这样的图书馆也可以使用。

这不会将其转换为地图。但你可以做你想做的所有事情。

答案 10 :(得分:1)

想象一下,你有一个如下所示的电子邮件列表。不受任何编程语言的限制,

emailsList = ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]

现在以下是JAVA代码 - 用于将json转换为map

JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList);
Map<String, Object> s = jsonObj.getMap();

答案 11 :(得分:1)

简短而有用:

/**
 * @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;
}

感谢@Vikas Gupta

答案 12 :(得分:1)

如果您讨厌递归-使用Stack和javax.json将Json字符串转换为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);
    }
}

答案 13 :(得分:1)

有一个使用 javax.json 发布的旧答案 here,但它只转换 JsonArrayJsonObject,但仍然有 JsonString、{{1} } 和 JsonNumber 输出中的包装类。如果你想摆脱这些,这是我的解决方案,它将解开一切。

除此之外,它使用 Java 8 流并包含在单个方法中。

JsonValue

答案 14 :(得分:0)

以下解析器读取文件,使用Google的JsonElement方法将其解析为通用JsonParser.parse,然后将生成的JSON中的所有项目转换为本机Java {{ 1}}或List<object>

注意 :以下代码基于Vikas Gupta&#39; answer < / p>

GsonParser.java

Map<String, Object>

FileLoader.java

import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

public class GsonParser {
    public static void main(String[] args) {
        try {
            print(loadJsonArray("data_array.json", true));
            print(loadJsonObject("data_object.json", true));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void print(Object object) {
        System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(object).toString());
    }

    public static Map<String, Object> loadJsonObject(String filename, boolean isResource)
            throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return jsonToMap(loadJson(filename, isResource).getAsJsonObject());
    }

    public static List<Object> loadJsonArray(String filename, boolean isResource)
            throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return jsonToList(loadJson(filename, isResource).getAsJsonArray());
    }

    private static JsonElement loadJson(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return new JsonParser().parse(new InputStreamReader(FileLoader.openInputStream(filename, isResource), "UTF-8"));
    }

    public static Object parse(JsonElement json) {
        if (json.isJsonObject()) {
            return jsonToMap((JsonObject) json);
        } else if (json.isJsonArray()) {
            return jsonToList((JsonArray) json);
        }

        return null;
    }

    public static Map<String, Object> jsonToMap(JsonObject jsonObject) {
        if (jsonObject.isJsonNull()) {
            return new HashMap<String, Object>();
        }

        return toMap(jsonObject);
    }

    public static List<Object> jsonToList(JsonArray jsonArray) {
        if (jsonArray.isJsonNull()) {
            return new ArrayList<Object>();
        }

        return toList(jsonArray);
    }

    private static final Map<String, Object> toMap(JsonObject object) {
        Map<String, Object> map = new HashMap<String, Object>();

        for (Entry<String, JsonElement> pair : object.entrySet()) {
            map.put(pair.getKey(), toValue(pair.getValue()));
        }

        return map;
    }

    private static final List<Object> toList(JsonArray array) {
        List<Object> list = new ArrayList<Object>();

        for (JsonElement element : array) {
            list.add(toValue(element));
        }

        return list;
    }

    private static final Object toPrimitive(JsonPrimitive value) {
        if (value.isBoolean()) {
            return value.getAsBoolean();
        } else if (value.isString()) {
            return value.getAsString();
        } else if (value.isNumber()){
            return value.getAsNumber();
        }

        return null;
    }

    private static final Object toValue(JsonElement value) {
        if (value.isJsonNull()) {
            return null;
        } else if (value.isJsonArray()) {
            return toList((JsonArray) value);
        } else if (value.isJsonObject()) {
            return toMap((JsonObject) value);
        } else if (value.isJsonPrimitive()) {
            return toPrimitive((JsonPrimitive) value);
        }

        return null;
    }
}

答案 15 :(得分:0)

这是一个古老的问题,也许仍然与某人有关。
假设您有字符串HashMap hash和JsonObject jsonObject

1)定义键列表。
示例:

ArrayList<String> keyArrayList = new ArrayList<>();  
keyArrayList.add("key0");   
keyArrayList.add("key1");  

2)创建foreach循环,从hash中添加jsonObject并添加:

for(String key : keyArrayList){  
    hash.put(key, jsonObject.getString(key));
}

那是我的方法,希望它能回答问题。

答案 16 :(得分:0)

使用Jackson进行转换:

JSONObject obj = new JSONObject().put("abc", "pqr").put("xyz", 5);

Map<String, Object> map = new ObjectMapper().readValue(obj.toString(), new TypeReference<Map<String, Object>>() {});

答案 17 :(得分:-1)

使用json-simple,您可以将数据JSON转换为Map以及将Map转换为JSON。

try
{
    JSONObject obj11 = new JSONObject();
    obj11.put(1, "Kishan");
    obj11.put(2, "Radhesh");
    obj11.put(3, "Sonal");
    obj11.put(4, "Madhu");

    Map map = new  HashMap();

    obj11.toJSONString();

    map = obj11;

    System.out.println(map.get(1));


    JSONObject obj12 = new JSONObject();

    obj12 = (JSONObject) map;

    System.out.println(obj12.get(1));
}
catch(Exception e)
{
    System.err.println("EROR : 01 :"+e);
}