[英]Android Studio volley nested jsonarray
我正在嘗試獲取 json 字符串的標題值(一旦它作為一個對象開始,一次作為一個數組)
我設法得到了結果,但它給了我額外的括號等。
title: {"value":"New Beginnings"}
而不僅僅是
title: New Beginnings
我正在嘗試的 2 個網址是
https://jhookcrochet.eu/categories/yarniversity/rest?_format=json
對此的任何幫助將不勝感激! 我想出的代碼是:
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url = "https://jhookcrochet.eu/?_format=json";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String json = "";
//txt.setText(response.toString());
try {
new JSONObject(response);
json = "object";
} catch (JSONException ex) {
json = "array";
}
if (json == "array") {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jresponse =
jsonArray.getJSONObject(i);
String title = jresponse.getString("title");
//String field_image = jresponse.getString("field_image");
String body = jresponse.getString("body");
Log.d("title", title);
//Log.d("field_image",field_image);
Log.d("body", body);
textView.append("Title: " + title + "\n");
}
} catch (JSONException e) {
textView.append("NO\n");
e.printStackTrace();
}
}
else if (json == "object") {
textView.append("Yep, that is an object\n");
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray gettitle = jsonResponse.optJSONArray("title");
for (int j=0;j<gettitle.length(); j++)
{
String title = gettitle.getString(j);
Log.d("title", title);
}
//textView.append("Title: " + title + "\n");
//Log.d("title", title);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
rq.add(request);
// Inflate the layout for this fragment
return root;
我實際上只是設法按照我想要的方式展示。
JSONArray jsonArray = jsonResponse.getJSONArray("title");
JSONObject titlevalue = jsonArray.getJSONObject(0);
String title = titlevalue.getString("value");
這將給出我想要的結果。
Title: New Beginnings
如果有人也在尋找這個,這是我的剪輯。 可能是一個更好更好的方法,但這目前對我有用:)
else if (json == "object") {
//textView.append("Yep, that is an object\n");
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonArray = jsonResponse.getJSONArray("title");
JSONObject titlevalue = jsonArray.getJSONObject(0);
String title = titlevalue.getString("value");
JSONArray jsonBody = jsonResponse.getJSONArray("body");
JSONObject bodyvalue = jsonBody.getJSONObject(0);
String body = bodyvalue.getString("value");
Log.d("title", title);
Log.d("body", body);
TitleView.append(title);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(body, Html.FROM_HTML_MODE_COMPACT));
} else {
textView.setText(Html.fromHtml(body));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.