Android Studio volley nested jsonarray



我试图获得json字符串的标题值(一开始作为对象,一开始作为数组)

我设法得到了一个结果,但是它给了我额外的括号等等。

title: {"value":"New Beginnings"}

而不是

title: New Beginnings

我正在尝试的两个url是

https://jhookcrochet.eu/categories/yarniversity/rest?_format = json

https://jhookcrochet.eu/?_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("NOn");
e.printStackTrace();
}
}
else if (json == "object") {
textView.append("Yep, that is an objectn");
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 objectn");
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();
}
}