简体   繁体   English

无法使用GSON解析/读取JSON

[英]Unable to parse/read JSON using GSON

I'm utilizing GSON library to parse a simple JSON, that has similar key-value pairs on all the objects (not limited to 4) as shown below: 我正在使用GSON库来解析一个简单的JSON,该JSON在所有对象上具有相似的键值对(不限于4个),如下所示:

[
  {
    "A": "xyz",
    "B": "mno",
    "C": 368,
    "E": 1,
    "F": "pqr"
  },
  {
    "A": "qwe",
    "B": "def",
    "C": 338,
    "D": 7,
    "E": 1,
    "F": null
  },

  {...
  },

  {...
  }
]

As soon as I read/iterate the GSON reader in order to parse the values, I get 当我阅读/迭代GSON阅读器以解析值时,我得到

Expected BEGIN_OBJECT but was STRING on line 7 of the following code

I've tried various combination of reading and iterating, but I fail to understand the logic behind using while (reader.hasNext()) 我尝试了读取和迭代的各种组合,但是我无法理解使用while(reader.hasNext())背后的逻辑。

reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();    
            while (reader.hasNext()) {
                if (reader.nextName().equals("A")) {    
                    while (reader.hasNext()) {
                        reader.beginObject();
                        while (reader.hasNext()) {
                            readPostObject(reader, queue);
                        }
                        reader.endObject();   

                    }
                } else {
                    reader.skipValue();
                }   

            }
            reader.endObject();    
        }
        reader.endArray();
    }

It would be great if anyone one can shed some light? 如果有人能阐明一点就好了吗?

As was mentioned earlier, Gson is a great tool for parsing JSON into plain Java objects. 如前所述,Gson是将JSON解析为纯Java对象的绝佳工具。

See example below (written in Kotlin): 请参阅以下示例(用Kotlin编写):

data class Abc(val A: String, val B: String, val C: Int, val E: Int, val F: String)

fun parseAbcList(json: String): List<Abc> {
   return Gson().fromJson<List<Abc>>(json, object : TypeToken<List<Abc>>() {}.type)
}

Here's a sample of how you could do it with Java objects (like I mentioned in my comment): 这是如何使用Java对象的示例(如我在评论中提到的那样):

class MyJsonObject {

  public String A;
  public String B;
  public Integer C;
  public Integer D;
  public Integer E;
  public String F;

}

// Serialization
Gson gson = new Gson();
List<MyJsonObject> myJsonObjects = gson.toJson(MyJsonObject[].class);
System.out.println(myJsonObjects[0].A); // xyz

This is the recommended way to parse JSON with GSON. 这是使用GSON解析JSON的推荐方法。

Assuming you do not explicitly need to use Reader : basically your JSON contains an Array or a List of Map s. 假设您不需要显式使用Reader :基本上,您的JSON包含一个ArrayMapList Deserializing is easy if you know what you need as a result and howto tell Gson what you are deserializing. 如果您知道结果需要什么并且如何告诉Gson您正在反序列化什么,反序列化将很容易。

Two examples below: 以下是两个示例:

@SuppressWarnings("unchecked")
List<Map<?, ?>> mapList = new Gson().fromJson(JSON, List.class);

Above will deserialize any generic type of map and guesses the type of values. 上面将反序列化任何通用类型的map并猜测值的类型。 This would produce something like ArrayList<Map<String, Object> where values are String s or Double s. 这将产生类似ArrayList<Map<String, Object>ArrayList<Map<String, Object>其中值是StringDouble

To excplicitly tell Map s generic type something like this could be done: 为了明确地告诉Map的泛型类型,可以执行以下操作:

Type tMap = TypeToken.getParameterized(Map.class, String.class, String.class).getType();
Type tjson = TypeToken.getArray(tMap).getType();

Map<String, String>[] mapList = new Gson().fromJson(json, tjson);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM