Hello I have a json response as part of a request i need to access the value of one of the attribute. For example, my response looks like:
{
"data": {
"Members": [
{
"id": "01",
"name": "new york"
},
{
"id": "02",
"name": "chicago"
}
,
{
"id": "03",
"name": "la"
}
]
}
}
I need to extract the values "new york" , "chicago", "la". How can i do it; i tried to convert to JSON object but unable to access even "data".:
JSONObject jsonObj = new JSONObject(response.getBody());
JSONArray ja_data = jsonObj.getJSONArray("data");
The above code is one among various googled answers and this one results in IllegalAccessException
. The complete exception:
Exception in thread "main" java.lang.RuntimeException: java.lang.IllegalAccessException: class org.json.JSONObject cannot access a member of class java.lang.String (in module java.base) with modifiers "private"
at org.json.JSONObject.populateInternalMap(JSONObject.java:349)
at org.json.JSONObject.<init>(JSONObject.java:278)
at GetName.getName(GetName.java:64)
at GetName.main(GetName.java:30)
Caused by: java.lang.IllegalAccessException: class org.json.JSONObject cannot access a member of class java.lang.String (in module java.base) with modifiers "private"
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
at java.base/java.lang.reflect.Method.invoke(Method.java:558)
at org.json.JSONObject.populateInternalMap(JSONObject.java:328)
Is there a way i can handle this. Thanks
CodePudding user response:
I think your issue is not related to the parsing of the JSON as I tested it as below :
// Escaped JSON String, same as presented in question
JSONObject jsonObj = new JSONObject("{\r\n \"data\": {\r\n \"Members\": [\r\n {\r\n \"id\": \"01\",\r\n \"name\": \"new york\"\r\n \r\n },\r\n {\r\n \"id\": \"02\",\r\n \"name\": \"chicago\" \r\n }\r\n ,\r\n {\r\n \"id\": \"03\",\r\n \"name\": \"la\" \r\n }\r\n ]\r\n }\r\n}");
// Parsed "data" as Object
JSONObject data = jsonObj.getJSONObject("data");
// Parsed "Members" as an array
JSONArray arr = data.getJSONArray("Members");
// Selected First Internal Object inside Array of "Members"
JSONObject obje = arr.getJSONObject(0);
// Printed out the "name" which is "new york"
System.out.println(obje.getString("name"));
The above code works according to the JSON given and parsed correctly. I think please investigate your response
object's access modifiers.
Alternatively, you can use GSON or Jackson to parse your JSON.
CodePudding user response:
you can retreive the values like below
JSONObject jsonObj = new JSONObject(response.getBody());
JSONObject ja_data = jsonObj.getJSONObject("data");
JSONArray jaarr = ja_data.getJSONArray("Members");
JSONObject obj1 = jaarr.getJSONObject(0);
System.out.println(obj1.getString("name"));
It prints "new york"