Reputation: 1943
I have a JSON structure like below and I cannot reach to the image node in no way. How can I do that with Volley library? Any ideas will be helpful. Thanks in advance.
{
"nodes": [
{
"node": {
"id": "2536",
"title": "Die Düsseldorfer Rabbiner",
"image": {
"src": "how to reach here",
"alt": "",
"title": "© Landeshauptstadt Düsseldorf/Michael Gstettenbauer"
},
"body": "some text",
"category": "Deutsch",
"created": "1481344134",
"url": "some text"
}
}
]
}
Code Block
JsonArrayRequest getRequest = new JsonArrayRequest(
url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject = new JSONObject("response");
JSONArray jsonArray = jsonObject.getJSONArray("nodes");
for(int i = 0; i<jsonArray.length(); i++){
JSONObject jo = jsonArray .getJSONObject(i);
String name = jo.getString("category");
Toast.makeText(context, name, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 0
Views: 43
Reputation: 73
From the look of things you should use JsonObjectRequest instead JsonArrayRequest.
JsonObjectRequest request=new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("nodes");
for(int i=0;i<array.length();i++){
JSONObject object= array.getJSONObject(i);
JSONObject imageObject= object.getJSONObject("node").getJSONObject("image");
Toast.makeText(TestActivity.this, imageObject.toString(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Upvotes: 1
Reputation: 15155
Your Java model should match the JSON exactly. The base element in your JSON schema is an object, not an array; therefore your request should be a JSONObjectRequest
, not a JSONArrayRequest
:
JSONObjectRequest request = new JSONObjectRequest(url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONArray response) {
try {
JSONArray nodes = response.getJSONArray("nodes");
for(int i = 0; i < nodes.length; i++) {
JSONObject obj = nodes.getJSONObject(i);
JSONObject node = obj.getJSONObject("node");
JSONObject image = node.getJSONObject("image");
String title = image.getString("title");
Toast.makeText(context, title, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
As you might be able to see, this can get tedious if you have a large dataset. Which is why I highly recommend using a JSON parsing library; such as GSON, Moshi or Jackson. There is a good tutorial on how to make a custom request with Volley to make use of these libraries in the training documentation.
Upvotes: 1