Android 如何使用Volley在JSON中的数组中获取数组中的元素
我能够从JSON页面获取一些信息,但是我很难获取数组中的元素 到目前为止,我的代码是:Android 如何使用Volley在JSON中的数组中获取数组中的元素,android,json,android-volley,Android,Json,Android Volley,我能够从JSON页面获取一些信息,但是我很难获取数组中的元素 到目前为止,我的代码是: @Override public void onResponse(JSONObject response) { try { String status = response.getString("status"); if (status.equals("ok")) { JSONArray jsonArray = response.g
@Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
if (status.equals("ok")) {
JSONArray jsonArray = response.getJSONArray("articles");
JSONObject jsonObject = jsonArray.getJSONObject(0);
titleTextView.setText(jsonObject.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
我收到JSON的页面是:
到目前为止,我的代码从第一篇文章中获取信息,除了从名为“source”的数组中
我想在名为“name”的名为“source”的数组中获取信息。“source”不是JSONArray
itsJSONObject
要从源
对象获取名称
,请尝试以下操作
if (status.equals("ok")) {
JSONArray jsonArray = response.getJSONArray("articles");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject sourceObject= jsonObject.getJSONObject("source");
titleTextView.setText(sourceObject.getString("name"));
}
根据api,源是一个对象而不是数组。
通过解析“源”对象并获取与其中“名称”键对应的字符串值,可以轻松访问“源”对象中的“名称”
@Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
if (status.equals("ok")) {
JSONArray jsonArray = response.getJSONArray("articles");
JSONObject jsonObject = jsonArray.getJSONObject(0);
titleTextView.setText(jsonObject.getString("title"));
JSONObject source = jsonObject.getJSONObject("source");
sourceNameTextView.setText(source.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
source
不是JSONArray
itsJSONObject
,请检查我的答案,希望这对您有所帮助。