【发布时间】:2019-01-07 19:12:18
【问题描述】:
我正在尝试将以下 JSON 数据解析为回收站视图。特别是我想解析地址对象以显示locationName、line1、city、state和zip,但是我无法正确解析方法。
{
"pollingLocations": [
{
"address": {
"locationName": "LITTLE LEAGUE HEADQUARTERS",
"line1": "6707 LITTLE LEAGUE DR",
"city": "SAN BERNARDINO",
"state": "CA",
"zip": "92407"
},
"notes": "",
"pollingHours": "07:00-20:00",
"sources": [
{
"name": "Voting Information Project",
"official": true
}
]
}
]
}
我的问题是找到地址对象。使用当前代码,我收到一个 logcat 错误,显示没有 locationName 的值。我认为这是因为我首先需要指定要迭代的地址对象,但是我该怎么做呢?这是我现在拥有的当前实现。
//fetch
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("pollingLocations");
for(int i = 0; i < array.length(); i++){
JSONObject addressObject = array.getJSONObject(i);
for (int x = 0; x < addressObject.length(); x++){
VotingLoc votingLoc = new VotingLoc(addressObject.getString("locationName"),
addressObject.getString("line1"),
addressObject.getString("city"),
addressObject.getString("state"),
addressObject.getString("zip"),
addressObject.getString("pollingHours"));
votingList.add(votingLoc);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
有更简单的方法吗?我相信我的 rvadapter 类的代码是正确的,错误出在这个方法中,但是如果您想查看任何其他代码,请告诉我。
【问题讨论】:
-
你缺少节点
address -
这就是我的想法,但是当我为地址创建一个 jsonObject 时,logcat 错误然后说地址没有值。您能否更具体地说明您将如何实现这一点?
-
我需要在场景中嵌套for循环吗?没有人怎么办?