309

我正在从以 JSON 格式返回数据的服务器请求数据。在发出请求时将 HashMap 转换为 JSON 一点也不难,但另一种方式似乎有点棘手。JSON 响应如下所示:

{ 
    "header" : { 
        "alerts" : [ 
            {
                "AlertID" : "2",
                "TSExpires" : null,
                "Target" : "1",
                "Text" : "woot",
                "Type" : "1"
            },
            { 
                "AlertID" : "3",
                "TSExpires" : null,
                "Target" : "1",
                "Text" : "woot",
                "Type" : "1"
            }
        ],
        "session" : "0bc8d0835f93ac3ebbf11560b2c5be9a"
    },
    "result" : "4be26bc400d3c"
}

什么方法最容易访问这些数据?我正在使用 GSON 模块。

4

16 回答 16

506

干得好:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type);
于 2013-04-11T07:39:28.693 回答
120

此代码有效:

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());
于 2012-09-06T09:03:57.350 回答
78

我知道这是一个相当古老的问题,但我正在寻找一种将嵌套 JSON 反序列化为 a 的解决方案,但Map<String, Object>一无所获。

我的 yaml 反序列化程序的工作方式是,Map<String, Object>当您未指定类型时,它会将 JSON 对象默认为,但 gson 似乎没有这样做。幸运的是,您可以使用自定义反序列化器来完成它。

我使用下面的反序列化器自然反序列化任何东西,默认JsonObjects 为Map<String, Object>JsonArrays 为Object[]s,所有的孩子都被类似地反序列化。

private static class NaturalDeserializer implements JsonDeserializer<Object> {
  public Object deserialize(JsonElement json, Type typeOfT, 
      JsonDeserializationContext context) {
    if(json.isJsonNull()) return null;
    else if(json.isJsonPrimitive()) return handlePrimitive(json.getAsJsonPrimitive());
    else if(json.isJsonArray()) return handleArray(json.getAsJsonArray(), context);
    else return handleObject(json.getAsJsonObject(), context);
  }
  private Object handlePrimitive(JsonPrimitive json) {
    if(json.isBoolean())
      return json.getAsBoolean();
    else if(json.isString())
      return json.getAsString();
    else {
      BigDecimal bigDec = json.getAsBigDecimal();
      // Find out if it is an int type
      try {
        bigDec.toBigIntegerExact();
        try { return bigDec.intValueExact(); }
        catch(ArithmeticException e) {}
        return bigDec.longValue();
      } catch(ArithmeticException e) {}
      // Just return it as a double
      return bigDec.doubleValue();
    }
  }
  private Object handleArray(JsonArray json, JsonDeserializationContext context) {
    Object[] array = new Object[json.size()];
    for(int i = 0; i < array.length; i++)
      array[i] = context.deserialize(json.get(i), Object.class);
    return array;
  }
  private Object handleObject(JsonObject json, JsonDeserializationContext context) {
    Map<String, Object> map = new HashMap<String, Object>();
    for(Map.Entry<String, JsonElement> entry : json.entrySet())
      map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class));
    return map;
  }
}

handlePrimitive方法内部的混乱是为了确保您只能获得 Double 或 Integer 或 Long,并且可能会更好,或者如果您可以接受 BigDecimals,至少可以简化,我认为这是默认设置。

您可以像这样注册此适配器:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();

然后这样称呼它:

Object natural = gson.fromJson(source, Object.class);

我不确定为什么这不是 gson 中的默认行为,因为它在大多数其他半结构化序列化库中......

于 2011-01-25T22:29:03.640 回答
38

使用谷歌的 Gson 2.7(也可能是早期版本,但我使用当前版本 2.7 进行了测试),它很简单:

Map map = gson.fromJson(jsonString, Map.class);

它返回 aMap类型com.google.gson.internal.LinkedTreeMap并递归地作用于嵌套对象、数组等。

我像这样运行 OP 示例(简单地将双引号替换为单引号并删除空格):

String jsonString = "{'header': {'alerts': [{'AlertID': '2', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}, {'AlertID': '3', 'TSExpires': null, 'Target': '1', 'Text': 'woot', 'Type': '1'}], 'session': '0bc8d0835f93ac3ebbf11560b2c5be9a'}, 'result': '4be26bc400d3c'}";
Map map = gson.fromJson(jsonString, Map.class);
System.out.println(map.getClass().toString());
System.out.println(map);

并得到以下输出:

class com.google.gson.internal.LinkedTreeMap
{header={alerts=[{AlertID=2, TSExpires=null, Target=1, Text=woot, Type=1}, {AlertID=3, TSExpires=null, Target=1, Text=woot, Type=1}], session=0bc8d0835f93ac3ebbf11560b2c5be9a}, result=4be26bc400d3c}
于 2016-09-12T06:01:31.020 回答
31

新 Gson 库的更新:
您现在可以直接将嵌套的 Json 解析为 Map,但如果您尝试将 Json 解析为类型,您应该注意Map<String, Object>:它会引发异常。要解决此问题,只需将结果声明为LinkedTreeMap类型。下面的例子:

String nestedJSON = "{\"id\":\"1\",\"message\":\"web_didload\",\"content\":{\"success\":1}}";
Gson gson = new Gson();
LinkedTreeMap result = gson.fromJson(nestedJSON , LinkedTreeMap.class);
于 2013-12-12T07:46:27.433 回答
13

我有完全相同的问题并最终来到这里。我有一种看起来更简单的不同方法(也许是新版本的 gson?)。

Gson gson = new Gson();
Map jsonObject = (Map) gson.fromJson(data, Object.class);

使用以下 json

{
  "map-00": {
    "array-00": [
      "entry-00",
      "entry-01"
     ],
     "value": "entry-02"
   }
}

以下

Map map00 = (Map) jsonObject.get("map-00");
List array00 = (List) map00.get("array-00");
String value = (String) map00.get("value");
for (int i = 0; i < array00.size(); i++) {
    System.out.println("map-00.array-00[" + i + "]= " + array00.get(i));
}
System.out.println("map-00.value = " + value);

输出

map-00.array-00[0]= entry-00
map-00.array-00[1]= entry-01
map-00.value = entry-02

您可以在导航 jsonObject 时使用 instanceof 动态检查。就像是

Map json = gson.fromJson(data, Object.class);
if(json.get("field") instanceof Map) {
  Map field = (Map)json.get("field");
} else if (json.get("field") instanceof List) {
  List field = (List)json.get("field");
} ...

它对我有用,所以它必须对你有用;-)

于 2014-09-09T14:13:52.550 回答
9

自 gson 2.8.0 起支持以下

public static Type getMapType(Class keyType, Class valueType){
    return TypeToken.getParameterized(HashMap.class, keyType, valueType).getType();
}

public static  <K,V> HashMap<K,V> fromMap(String json, Class<K> keyType, Class<V> valueType){
    return gson.fromJson(json, getMapType(keyType,valueType));
}
于 2018-03-01T06:35:18.423 回答
3

试试这个,它会起作用的。我将它用于Hashtable

public static Hashtable<Integer, KioskStatusResource> parseModifued(String json) {
    JsonObject object = (JsonObject) new com.google.gson.JsonParser().parse(json);
    Set<Map.Entry<String, JsonElement>> set = object.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();

    Hashtable<Integer, KioskStatusResource> map = new Hashtable<Integer, KioskStatusResource>();

    while (iterator.hasNext()) {
        Map.Entry<String, JsonElement> entry = iterator.next();

        Integer key = Integer.parseInt(entry.getKey());
        KioskStatusResource value = new Gson().fromJson(entry.getValue(), KioskStatusResource.class);

        if (value != null) {
            map.put(key, value);
        }

    }
    return map;
}

KioskStatusResource替换为您的类,将Integer替换为您的关键类。

于 2012-09-14T10:50:05.127 回答
2

这是我一直在使用的:

public static HashMap<String, Object> parse(String json) {
    JsonObject object = (JsonObject) parser.parse(json);
    Set<Map.Entry<String, JsonElement>> set = object.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
    HashMap<String, Object> map = new HashMap<String, Object>();
    while (iterator.hasNext()) {
        Map.Entry<String, JsonElement> entry = iterator.next();
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        if (!value.isJsonPrimitive()) {
            map.put(key, parse(value.toString()));
        } else {
            map.put(key, value.getAsString());
        }
    }
    return map;
}
于 2011-11-10T14:42:39.677 回答
2

这是一个可以做到的单线:

HashMap<String, Object> myMap =
   gson.fromJson(yourJson, new TypeToken<HashMap<String, Object>>(){}.getType());
于 2018-04-12T16:00:38.287 回答
1

我已经用自定义 JsonDeSerializer 克服了类似的问题。我试着让它有点通用,但仍然不够。这是一个适合我需要的解决方案。

首先,您需要为 Map 对象实现一个新的 JsonDeserializer。

public class MapDeserializer<T, U> implements JsonDeserializer<Map<T, U>>

反序列化方法看起来与此类似:

public Map<T, U> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

        if (!json.isJsonObject()) {
            return null;
        }

        JsonObject jsonObject = json.getAsJsonObject();
        Set<Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
        Map<T, U> deserializedMap = new HashMap<T, U>();

        for (Entry<java.lang.String, JsonElement> entry : jsonEntrySet) {
            try {
                U value = context.deserialize(entry.getValue(), getMyType());
                deserializedMap.put((T) entry.getKey(), value);
            } catch (Exception ex) {
                logger.info("Could not deserialize map.", ex);
            }
        }

        return deserializedMap;
    }

这个解决方案的缺点是我的 Map 的键始终是“String”类型。然而,通过改变一些东西,有人可以使它通用。另外,我需要说的是,值的类应该在构造函数中传递。所以getMyType()我的代码中的方法返回 Map 值的类型,它是在构造函数中传递的。

你可以参考这篇文章How do I write a custom JSON deserializer for Gson? 为了了解有关自定义反序列化程序的更多信息。

于 2013-03-01T12:47:40.943 回答
1

你可以改用这个类: )(处理偶数列表、嵌套列表和json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


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


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

要将您的JSON 字符串转换为 hashmap,请使用以下命令:

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
于 2018-07-01T07:55:39.620 回答
0

这更像是凯文·多兰的答案的附录,而不是完整的答案,但我在从数字中提取类型时遇到了麻烦。这是我的解决方案:

private Object handlePrimitive(JsonPrimitive json) {
  if(json.isBoolean()) {
    return json.getAsBoolean();
  } else if(json.isString())
    return json.getAsString();
  }

  Number num = element.getAsNumber();

  if(num instanceof Integer){
    map.put(fieldName, num.intValue());
  } else if(num instanceof Long){
    map.put(fieldName, num.longValue());
  } else if(num instanceof Float){
    map.put(fieldName, num.floatValue());
  } else {    // Double
     map.put(fieldName, num.doubleValue());
  }
}
于 2018-10-06T01:26:14.973 回答
-1
 HashMap<String, String> jsonToMap(String JsonDetectionString) throws JSONException {

    HashMap<String, String> map = new HashMap<String, String>();
    Gson gson = new Gson();

    map = (HashMap<String, String>) gson.fromJson(JsonDetectionString, map.getClass());

    return map;

}
于 2017-09-21T19:38:49.743 回答
-3

JSONObject 通常HashMap在内部使用来存储数据。因此,您可以在代码中将其用作 Map。

例子,

JSONObject obj = JSONObject.fromObject(strRepresentation);
Iterator i = obj.entrySet().iterator();
while (i.hasNext()) {
   Map.Entry e = (Map.Entry)i.next();
   System.out.println("Key: " + e.getKey());
   System.out.println("Value: " + e.getValue());
}
于 2010-05-06T09:49:01.593 回答
-3

我使用了这段代码:

Gson gson = new Gson();
HashMap<String, Object> fields = gson.fromJson(json, HashMap.class);
于 2015-04-21T15:06:36.260 回答