Java 将 JSONObject 转换为 Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21544973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:17:51  来源:igfitidea点击:

Convert JSONObject to Map

javajsonmapjsonobject

提问by Marco C

I have a JSONObjectwith some attributes that I want to convert into a Map<String, Object>

我有JSONObject一些我想转换成的属性Map<String, Object>

Is there something that I can use from the json.org or ObjectMapper?

有什么我可以从 json.org 或 使用的东西ObjectMapper吗?

采纳答案by A Paul

use Hymanson(http://Hymanson.codehaus.org/) from http://json.org/

使用来自http://json.org/ 的Hymanson( http://Hymanson.codehaus.org/)

HashMap<String,Object> result =
        new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);

回答by Stijn V

Note to the above solution (from A Paul): The solution doesn't work, cause it doesn't reconstructs back a HashMap< String, Object > - instead it creates a HashMap< String, LinkedHashMap >.

上述解决方案的注意事项(来自 A Paul):该解决方案不起作用,因为它不会重构回 HashMap< String, Object > - 而是创建了 HashMap< String, LinkedHashMap >。

Reason why is because during demarshalling, each Object (JSON marshalled as a LinkedHashMap) is used as-is, it takes 1-on-1 the LinkedHashMap (instead of converting the LinkedHashMap back to its proper Object).

原因是因为在解组过程中,每个对象(JSON 编组为 LinkedHashMap)按原样使用,它需要一对一的 LinkedHashMap(而不是将 LinkedHashMap 转换回其正确的对象)。

If you had a HashMap< String, MyOwnObject > then proper demarshalling was possible - see following example:

如果你有一个 HashMap< String, MyOwnObject > 那么适当的解组是可能的 - 请参见以下示例:

ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, MyOwnObject.class);
HashMap<String, MyOwnObject> map = mapper.readValue(new StringReader(hashTable.toString()), mapType);

回答by Stijn V

Found out these problems can be addressed by using

发现这些问题可以通过使用来解决

ObjectMapper#convertValue(Object fromValue, Class<T> toValueType)

As a result, the origal quuestion can be solved in a 2-step converison:

因此,原始问题可以通过两步转换来解决:

  1. Demarshall the JSON back to an object - in which the Map<String, Object>is demarshalled as a HashMap<String, LinkedHashMap>, by using bjectMapper#readValue().

  2. Convert inner LinkedHashMaps back to proper objects

  1. 使用 bjectMapper#readValue()将 JSON 解组回对象 - 在该对象中Map<String, Object>被解组为 a HashMap<String, LinkedHashMap>

  2. 将内部 LinkedHashMaps 转换回正确的对象

ObjectMapper mapper = new ObjectMapper(); Class clazz = (Class) Class.forName(classType); MyOwnObject value = mapper.convertValue(value, clazz);

ObjectMapper mapper = new ObjectMapper(); Class clazz = (Class) Class.forName(classType); MyOwnObject value = mapper.convertValue(value, clazz);

To prevent the 'classType' has to be known in advance, I enforced during marshalling an extra Map was added, containing <key, classNameString>pairs. So at unmarshalling time, the classType can be extracted dynamically.

为了防止必须提前知道“classType”,我在编组期间强制添加了一个额外的 Map,包含<key, classNameString>对。因此,在解组时,可以动态提取 classType。

回答by NSchorr

This is what worked for me:

这对我有用:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonobj.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            Object value = jsonobj.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;
}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java

其中大部分来自这个问题:How to convert JSONObject to new Map for its all keys using iterator java

回答by Manoranjan

You can use Gson() (com.google.gson) library if you find any difficulty using Hymanson.

如果您发现使用 Hymanson 有任何困难,您可以使用 Gson() (com.google.gson) 库。

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

回答by Paritosh Gupta

The best way to convert it to HashMap<String, Object>is this:

将其转换为的最佳方法HashMap<String, Object>是:

HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));