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);
}