英文:
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:
[
{"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"}
]
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("Group Name").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("Group Name").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<String> pmGrpListFromWebOm = new ArrayList<>();
for (JsonElement jsonObjectElement : jsonArray) {
JsonObject jsonObject = jsonObjectElement.getAsJsonObject();
String grpname= jsonObject.get("Group Name").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 < 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
}
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<ArrayList<Map<String, String>>>(){}.getType();
// read the list
List<Map<String, String>> list = gson.fromJson(json, itemListType);
// process items in the list
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);
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论