Я хочу получить этот JSON в Android с Volley. Как я могу это сделать?Получить JSON с Volley
{ "post": [ { "title": "a", "content": "a", "mobile": "a", "imageurl": "a" }, { "title": "b", "content": "b", "mobile": "b", "imageurl": "b" } ], "banner": [ { "title": "c", "content": "c", "mobile": "c", "imageurl": "c" }, { "title": "d", "content": "d", "mobile": "d", "imageurl": "d" } ] }
Это мой код в Java:
public void GetPost(JSONObject jsonObject, final onPostReceived onPostReceived) {
String url = "";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponseGetPost: " + response.toString());
try {
// iwant to get all posts and banners
//for example 20 post
// 2 banner
List<Post> postList = new ArrayList<>();
List<PostBanner> postBannerList = new ArrayList<>();
JSONArray json = response.getJSONArray("banner");
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
Post post = new Post();
PostBanner postBanner = new PostBanner();
JSONObject jsonObject = jsonArray.getJSONObject(i);
post.setImageUrl(jsonObject.getString("imageurl"));
post.setContent(jsonObject.getString("content"));
post.setTitle(jsonObject.getString("title"));
post.setMobile(jsonObject.getString("mobile"));
postList.add(post);
JSONObject jsonObject1 = json.getJSONObject(i);
postBanner.setTitle(jsonObject1.getString("title"));
postBanner.setContent(jsonObject1.getString("content"));
postBanner.setMobile(jsonObject1.getString("mobile"));
postBanner.setImageUrl(jsonObject1.getString("imageurl"));
postBannerList.add(postBanner);
onPostReceived.onReceived(postList, postBannerList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//log error
}
});
request.setRetryPolicy(new DefaultRetryPolicy(18000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
}
В чем проблема в этом коде? Он получает сообщения до длины баннера, но только один баннер, когда я запускаю приложение. Зачем?
какую ошибку вы получаете –
Вашего JSON является корректным –
Вы должны использовать вложенные циклы, когда вы разбор JSON. –