如何在不知道 json 键的情况下使用 JsonReader 从 json 中读取值

How to read the value from json using JsonReader without knowing the json key

我正在尝试使用 TypedArray 来解析 json。

我的 json 将是:

    {
      "id":"112233",
      "tag":"From server",
      "users":{
      "vijay":1,
      "dhas":2,
      "vijaydhas":3
      }
    }

此处用户对象键是动态的。我将在 运行 时间从服务器接收。只有那个时候我不知道钥匙(vijay, dhas, vijaydhas).

为了解析 id 和标签,我将执行以下代码。

           @Override
            public MagazineReader read (JsonReader in) throws IOException {

                final MagazineReader magazineReader = new MagazineReader();

                in.beginObject();
                while (in.hasNext()) {
                    switch (in.nextName()) {
                        case "id":
                            magazineReader.setID(in.nextInt());
                            break;
                        case "tag":
                            magazineReader.setTag(in.nextString());
                            break;
                            in.beginArray();
                            /*
                                                For User how to read the json???
                             */
                }
              in.endObject();
            }

现在我想在不知道密钥的情况下读取和解析用户 JsonArray 及其对象。我知道如何在不知道密钥的情况下解析 JSONObject。

JSONObject users= obj.getJSONObject("users");
            Iterator iteratorObj = detailList.keys();
            while (iteratorObj.hasNext())
            {
                String jsonKey = (String)iteratorObj.next();
                property.put(jsonKey,usersList.get(jsonKey));
            }

但是在 JsonReader 中,我不知道如何在不知道密钥的情况下读取 json 值。请帮我解决这个问题。 [1]: https://javacreed.com/gson-typeadapter-example

你可以这样做:

@Override
public MagazineReader read(JsonReader in) throws IOException {

  final MagazineReader magazineReader = new MagazineReader();
  final Map<String, Object> users = new HashMap<>();

  in.beginObject();
  while (in.hasNext()) {
    switch (in.nextName()) {
      case "id":
        magazineReader.setID(in.nextInt());
        break;
      case "tag":
        magazineReader.setTag(in.nextString());
        break;
      case "users":
        in.beginObject();
        while(in.hasNext()) {
          String key = in.nextName();
          JsonToken type = in.peek();
          if (type == JsonToken.NUMBER) {
            users.put(key, in.nextInt());
          } else if (type == JsonToken.STRING) {
            users.put(key, in.nextString());
          } else {
            System.err.println("Unhandled type: " + type);
          }
        }
        in.endObject();
        break;
    }
    in.endObject();
  }
}

我使用了 Map 来存储键值对,您可以使用任何类型的对象来存储键值对。另外,我只添加了数字和字符串值的处理程序。

重要的部分是当您到达 users 键时开始一个新对象,然后遍历该对象的所有属性。您如何处理对象的条目取决于您要做什么。