如何使用GSON在android中解析动态“key”的JSON

时间:2012-04-22 11:59:47

标签: android gson

我一直在使用GSON库来解析所有json字符串并获取一个JSON对象。 但现在我需要解析就是这样:

{
   "status":1,
   "info":[
      {
         "\u5a31\u4e50":"\u51b7\u76d8,\u9ad8\u811a\u676f,\u6211\u7684\u7cd6\u679c\u5c4b,\u670d\u52a1\u4e1a\u6d88\u8d39\u52b5"
      },
      {
         "\u7f8e\u5986":"\u4e2a\u62a4|\u5316\u5986#\u9762\u90e8\u62a4\u7406,\u4e2a\u4eba\u536b\u751f,\u8eab\u4f53\u62a4\u7406,\u9999\u6c34\u9999\u6c1b,\u6c90\u6d74|\u7f8e\u53d1\u7528\u54c1,\u5f69\u5986,\u7cbe\u6cb9SPA,\u773c\u90e8\u62a4\u7406,\u78e8\u7802\u53bb"
      },
      {
         "\u8863\u670d":"\u670d|\u9970|\u978b|\u5e3d#\u670d\u88c5,\u978b\u9774,\u5185\u8863,\u914d\u9970,\u536b\u8863,\u4f11\u95f2\u88e4,T\u6064,\u88d9\u5b50,\u886c\u886b,\u9488\u7ec7\u886b,\u5a74\u5e7c\u513f\u670d\u9970"
      }
   ],
   "total":3
}

关键字段是动态的,所以我不知道如何编写模型类来阅读它。

2 个答案:

答案 0 :(得分:11)

您希望模型类看起来如何?

statustotal可能是int,因此只留下info

作为一项实验,只需添加一个字段Object info,然后查看Gson如何将其设置为ArrayList<LinkedHashMap<String, String>> - 丑陋且难以通过密钥访问,但所有数据都在那里。鉴于这些信息,建模课程的最快方法是:

class Something {
  int status;
  List<Map<String, String> info;
  int total;
}

如果您可以控制JSON的生成方式,我建议将info的结构从对象数组[{a:b},{c:d},{e:f}]更改为对象{a:b,c:d,e:f}。有了这个,您只需将其映射到Map<String, String>即可获得所有好处,例如按键访问keys()values()

class Something {
  int status;
  Map<String, String> info;
  int total;
}

如果你想要后一个模型类而不改变JSON格式,你将不得不写一个TypeAdapter(或JsonDeserializer如果你只对解析JSON感兴趣,而不是从你的JSON生成它模特课)。

这是一个JsonDeserializer帽子会将您原来的info JSON属性映射到普通Map<String, String>

class ArrayOfObjectsToMapDeserializer
    implements JsonDeserializer<Map<String, String>> {

  public Map<String, String> deserialize(JsonElement json, Type typeOfT,
      JsonDeserializationContext context) throws JsonParseException {
    Map<String, String> result = new HashMap<String, String>();

    JsonArray array = json.getAsJsonArray();
    for (JsonElement element : array) {
      JsonObject object = element.getAsJsonObject();
      // This does not check if the objects only have one property, so JSON
      // like [{a:b,c:d}{e:f}] will become a Map like {a:b,c:d,e:f} as well.
      for (Entry<String, JsonElement> entry : object.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue().getAsString();
        result.put(key, value);
      }
    }
    return result;
  }
}

您需要注册与此类似的自定义JsonDeserializer

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(
    new TypeToken<Map<String, String>>() {}.getType(),
    new ArrayOfObjectsToMapDeserializer());
Gson gson = builder.create();

请注意,这会为任何Map<String, String>注册自定义反序列化程序,无论遇到什么类。如果你不想这样做,你还需要创建一个自定义TypeAdapterFactory并在返回之前检查声明类和反序列化器的实例。

答案 1 :(得分:1)

这是一个解决方案,它不需要制作JsonDeserializer。

您可以创建的所有内容都是地图Map.Entry<String, JsonElement>中的JsonElement,并使用for循环迭代条目

//parsing string response to json object
 JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonString);
  //getting root object
 JsonObject dateWiseContent = jsonObject.get("rootObject").getAsJsonObject();

        for (Map.Entry<String, JsonElement> entry : dateWiseContent.entrySet()) {

                   //this gets the dynamic keys
                    String  dateKey = entry.getKey();

                    //you can get any thing now json element,array,object according to json.

                    JsonArray jsonArrayDates = entry.getValue().getAsJsonArray();
        }

了解更多here