我希望像这样的json
解析嵌套的json但我以前不使用嵌套的json,我知道单独解析json对象和数组但我不知道嵌套的json解析。我想在title
中获取posts
并在tumbnail_images中获取tumbnail网址
我写了一些代码,但我有错误
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
final String posts = response.getString("posts");
// ================================================ Json Array Request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
String arrayResponse = "";
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = (JSONObject) response.get(i);
String title = post.getString("title");
arrayResponse += "title : " + title;
}
}
catch (JSONException e) {
e.printStackTrace();
}
//btnShow ClickListener
btnShowPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txtShowPosts.setText(arrayResponse);
}
});
}
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "We have a problem in Array Request ", Toast.LENGTH_SHORT).show();
}
});
jsonResponse = "";
jsonResponse += "posts " + posts;
);
}
catch(
JSONException e
)
{
e.printStackTrace();
Toast.makeText(MainActivity.this, "We have a problem ", Toast.LENGTH_SHORT).show();
}
}
}
,new Response.ErrorListener()
{
@Override
public void onErrorResponse (VolleyError error){
Toast.makeText(MainActivity.this, "We have a problem in volley ", Toast.LENGTH_SHORT).show();
}
}
);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
答案 0 :(得分:0)
传递你的json String,你将在这里得到所有的标题。
public ArrayList<String> getTitles(final JSONObject object){
ArrayList<String> returnData = new ArrayList<>();
try{
JSONArray postArray = object.getJSONArray("posts");
for(int x=0;x<postArray.length();x++){
returnData.add(postArray.getJSONObject(x).getString("title").toString());
}
}
catch (JSONException e){}
return returnData;
}
如何:在您的JSON字符串中,您必须以这种方式解析标题。