Reputation: 1852
I'm trying to read data from the following json object in Java HTTP post. I'm first converting it to string then json object to read the data.
{
"entry": [
{
"id": "1306487646057992",
"messaging": [
{
"message": {
"mid": "mid.1486361982003:2ed6c8ae51",
"seq": 12412,
"text": "hi there 8"
},
"recipient": {
"id": "1306487646057992"
},
"sender": {
"id": "1374961642574944"
},
"timestamp": 1486361982003
}
],
"time": 1486361982072
}
],
"object": "page"
}
Java Code..
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
JSONObject row = new JSONObject(data);
JSONArray rows = row.getJSONArray("entry");
JSONArray first = rows.getJSONArray(0);
System.out.println("first array is "+first);
When I run the code I keep getting the following exception
org.json.JSONException: JSONArray[0] is not a JSONArray.
I'm trying to access the sender id & text field "hi there 8" Can't understand where i'm going wrong..Please Help..
Upvotes: 0
Views: 593
Reputation: 2503
As you can clearly see from what JSON you have given that entry
is JSONArray
but first entity inside this array is not JSONObject
, it is simple a JSONObject
beacause of which you are getting the error.
As error says org.json.JSONException: JSONArray[0] is not a JSONArray
JSONArray[0]
is not JSONObject
its actually a JSONObject
.
JSONArray first = rows.getJSONArray(0);
Above line is causing the error because the returned object is JSONObject
not JSONArray
. So change it to,
JSONObject first = rows.getJSONObject(0);
Further to access message text
and sender id
you can the following,
JSONObject messageObject = rows.getJSONObject(0).getJSONArray("messaging").getJSONObject(0);
String text = messageObject.getJSONObject("message").getString("text");
String senderid = messageObject.getJSONObject("sender").getString("id");
Upvotes: 1