如何解决在Java中解析Json文件时出现 com.google.gson.JsonArray 无法转换的问题。

huangapple go评论68阅读模式
英文:

How to solve com.google.gson.JsonArray cannot be cast while parsing Json file in java

问题

我第一次在Java中解析JSON文件。我的JSON文件结构是固定的(无法更改)。我已经阅读了不同的答案,但没有帮助我解决我的JSON问题。
我想在一个ArrayList中获取所有的Group Name,在另一个ArrayList中获取Unit Name
请帮助解决这个错误,谢谢。

我使用了下面的代码尝试从JSON中读取,但是解析失败。

JSON文件:

[
    {"No":"1","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"UN","PM":"NULL"},
    {"No":"2","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"UM","PM":"NULL"},
    {"No":"3","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"UP","PM":"NULL"},
    {"No":"4","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"SO","PM":"NULL"},
    {"No":"5","Component":"Amazon","group_id":"1","Group Name":"cart","Unit Name":"SP","PM":"NULL"},
    {"No":"6","Component":"Amazon","group_id":"2","Group Name":"payment","Unit Name":"NZ","PM":"TRUE"}
]

代码尝试 1:

JsonArray jsonArray = new JsonArray();
Object obj = new JsonParser().parse(new FileReader(JSON_FILE_PATH));
JsonObject jsonObject = jsonArray.getAsJsonObject();
String groupName = jsonObject.get("Group Name").toString();

错误:在测试用例中出现异常(IllegalStateException: Not a JSON Object: [])。
java.lang.IllegalStateException: Not a JSON Object: []

代码尝试 2:

Object obj = new JsonParser().parse(new FileReader(JSON_FILE_PATH));
JsonObject jsonObject = (JsonObject) obj;
String firstName = jsonObject.get("Group Name").toString();

错误:在测试用例中出现异常(ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject)。
java.lang.ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject

我通过以下代码解决了这个问题:

JsonArray jsonArray = new JsonParser().parse(new FileReader(fileName)).getAsJsonArray();

ArrayList<String> pmGrpListFromWebOm = new ArrayList<>();
for (JsonElement jsonObjectElement : jsonArray) {
    JsonObject jsonObject = jsonObjectElement.getAsJsonObject();
    String grpname = jsonObject.get("Group Name").toString();
    pmGrpListFromWebOm.add(grpname);
}
英文:

I am parsing json file in java first time. Where my json file structure is fixed one (I can not change this). I have gone through different answers, but didn't help with my json.
I want list of all Group Name in one arrylist and Unit Name in another arraylist
Please help to resolve this error, Thanks
I used below code and tried to read from json, but failed to parsed.
JSON FILE:

[
    {&quot;No&quot;:&quot;1&quot;,&quot;Component&quot;:&quot;Amazon&quot;,&quot;group_id&quot;:&quot;1&quot;,&quot;Group Name&quot;:&quot;shop&quot;,&quot;Unit Name&quot;:&quot;UN&quot;,&quot;PM&quot;:&quot;NULL&quot;},
    {&quot;No&quot;:&quot;2&quot;,&quot;Component&quot;:&quot;Amazon&quot;,&quot;group_id&quot;:&quot;1&quot;,&quot;Group Name&quot;:&quot;shop&quot;,&quot;Unit Name&quot;:&quot;UM&quot;,&quot;PM&quot;:&quot;NULL&quot;},
    {&quot;No&quot;:&quot;3&quot;,&quot;Component&quot;:&quot;Amazon&quot;,&quot;group_id&quot;:&quot;1&quot;,&quot;Group Name&quot;:&quot;shop&quot;,&quot;Unit Name&quot;:&quot;UP&quot;,&quot;PM&quot;:&quot;NULL&quot;},
    {&quot;No&quot;:&quot;4&quot;,&quot;Component&quot;:&quot;Amazon&quot;,&quot;group_id&quot;:&quot;1&quot;,&quot;Group Name&quot;:&quot;shop&quot;,&quot;Unit Name&quot;:&quot;SO&quot;,&quot;PM&quot;:&quot;NULL&quot;},
    {&quot;No&quot;:&quot;5&quot;,&quot;Component&quot;:&quot;Amazon&quot;,&quot;group_id&quot;:&quot;1&quot;,&quot;Group Name&quot;:&quot;cart&quot;,&quot;Unit Name&quot;:&quot;SP&quot;,&quot;PM&quot;:&quot;NULL&quot;},
    {&quot;No&quot;:&quot;6&quot;,&quot;Component&quot;:&quot;Amazon&quot;,&quot;group_id&quot;:&quot;2&quot;,&quot;Group Name&quot;:&quot;payment&quot;,&quot;Unit Name&quot;:&quot;NZ&quot;,&quot;PM&quot;:&quot;TRUE&quot;}
]

Code Trial 1 :

JsonArray jsonArray = new JsonArray();
            Object obj = new JsonParser().parse(new FileReader(JSON_FILE_PATH));
            JsonObject jsonObject = jsonArray.getAsJsonObject();
            String groupName = jsonObject.get(&quot;Group Name&quot;).toString();
			

ERROR: Exception in Test Case: (IllegalStateException: Not a JSON Object: [])
java.lang.IllegalStateException: Not a JSON Object: []

Code Trial 2:

Object obj = new JsonParser().parse(new FileReader(JSON_FILE_PATH));
JsonObject jsonObject = (JsonObject) obj;            
String firstName = jsonObject.get(&quot;Group Name&quot;).toString();

 
ERROR: Exception in Test Case: (ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject)
java.lang.ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject

I have solved this issue with below code :

JsonArray jsonArray = new JsonParser().parse(new FileReader(fileName)).getAsJsonArray();
          
            ArrayList&lt;String&gt; pmGrpListFromWebOm = new ArrayList&lt;&gt;();
            for (JsonElement jsonObjectElement : jsonArray) {
                JsonObject jsonObject = jsonObjectElement.getAsJsonObject();
                String grpname= jsonObject.get(&quot;Group Name&quot;).toString();
                pmGrpListFromWebOm.add(grpname);
            }

答案1

得分: 2

以下是翻译后的内容:

JSON 文件包含对象的数组,因此您应该能够立即使用 parser.parse 方法和显式转换来读取 JsonArray

然后,您应该迭代该数组,并使用 get 方法访问其 JsonObject 项。

JsonParser parser = new JsonParser();
JsonArray jsonArray = (JsonArray) parser.parse(new FileReader(JSON_FILE_PATH));

for (int i = 0; i < jsonArray.size(); i++) {
    JsonObject item = (JsonObject) jsonArray.get(i);
    String groupName = item.get("Group Name").getAsString();
    System.out.printf("%d group=%s%n", i, groupName); // item index and groupName
}

输出将为:

0 group=shop
1 group=shop
2 group=shop
3 group=shop
4 group=cart
5 group=payment

然而,Gson 的 JsonParser 已被弃用,建议使用 Gson 对象映射器以更具类型安全性的方式读取/写入对象。

在示例 JSON 中,每个项都可以看作是键值对的映射,其中键和值都是字符串。

Gson gson = new Gson();

// 准备类型信息
Type itemListType = new TypeToken<ArrayList<Map<String, String>>>(){}.getType();

// 读取列表
List<Map<String, String>> list = gson.fromJson(json, itemListType);

// 处理列表中的项
for (Map<String, String> item : list) {
    String no = item.get("No");
    String groupName = item.get("Group Name");
    System.out.printf("no=%s group=%s%n", no, groupName);
}

输出:

no=1 group=shop
no=2 group=shop
no=3 group=shop
no=4 group=shop
no=5 group=cart
no=6 group=payment
英文:

The JSON file contains array of objects so you should be able to read the JsonArray immediately using parser.parse method and explicit casting.

Then you should iterate the array and access its JsonObject items using get method.

JsonParser parser = new JsonParser();
JsonArray jsonArray = (JsonArray) parser.parse(new FileReader(JSON_FILE_PATH));

for (int i = 0; i &lt; jsonArray.size(); i++) {
    JsonObject item = (JsonObject) jsonArray.get(i);
    String groupName = item.get(&quot;Group Name&quot;).getAsString();
    System.out.printf(&quot;%d group=%s%n&quot;, i, groupName); // item index and groupName
}

The output will be:

0 group=shop
1 group=shop
2 group=shop
3 group=shop
4 group=cart
5 group=payment

However, Gson JsonParser is deprecated and it is recommended to use Gson object mapper which allows to read/write objects in more type-safe way.

Each item in the example JSON can be considered as a map of key-value pairs, where both key and value are String.

Gson gson = new Gson();

// prepare type information
Type itemListType = new TypeToken&lt;ArrayList&lt;Map&lt;String, String&gt;&gt;&gt;(){}.getType();

// read the list
List&lt;Map&lt;String, String&gt;&gt; list = gson.fromJson(json, itemListType);

// process items in the list
for (Map&lt;String, String&gt; item : list) {
    String no = item.get(&quot;No&quot;);
    String groupName = item.get(&quot;Group Name&quot;);
    System.out.printf(&quot;no=%s group=%s%n&quot;, no, groupName);
}

output:

no=1 group=shop
no=2 group=shop
no=3 group=shop
no=4 group=shop
no=5 group=cart
no=6 group=payment

huangapple
  • 本文由 发表于 2020年10月20日 20:28:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64445182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定