我必须显示 JSON 数组中的对象列表。但我似乎无法打印出来
Posted
技术标签:
【中文标题】我必须显示 JSON 数组中的对象列表。但我似乎无法打印出来【英文标题】:I have to show a list of Objects from a JSON array. But i cant seem to print it out 【发布时间】:2021-09-01 10:17:59 【问题描述】:// 我已经在这里声明了一切,从这里看起来一切都很好。我觉得我这里没有问题
公共类 MainActivity 扩展 AppCompatActivity
private TextView mTextViewResult;
private RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
jsonParse();
);
private void jsonParse()
String url = "https://fetch-hiring.s3.amazonaws.com/hiring.json";
// 我不知道我的问题出在哪里,我已经声明了所有内容,但没有任何显示,我在想我应该声明一个数组而不是一个对象,但我仍然遇到困难
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
@Override
public void onResponse(JSONObject response)
try
JSONArray jsonArray = response.getJSONArray("");
for (int i = 0; i < jsonArray.length(); i++)
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
error.printStackTrace();
);
mQueue.add(request);
【问题讨论】:
您的 URL 是 JSONArray,无法从 JSONObjectRequest 解析 【参考方案1】:由于响应是一个Json Array,所以需要使用JsonArrayRequest而不是JsonObjectRequest,并且在onResponse中接收一个JSONArray。
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<org.json.JSONArray>()
@Override
public void onResponse(org.json.JSONArray response)
try
for (int i = 0; i < response.length(); i++)
..... etc.
见https://javadoc.io/static/com.android.volley/volley/1.1.1/com/android/volley/toolbox/JsonArrayRequest.html
【讨论】:
【参考方案2】:试试下面的代码。
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>()
@Override
public void onResponse(JSONArray response)
try
for (int i = 0; i < response.length(); i++)
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
error.printStackTrace();
);
mQueue.add(request);
【讨论】:
以上是关于我必须显示 JSON 数组中的对象列表。但我似乎无法打印出来的主要内容,如果未能解决你的问题,请参考以下文章
Java - 如何反序列化带有嵌套对象和列表的 JSON 数组? [复制]