我正在尝试解析以下API数据。我只需要在我的应用程序中使用开始时间,结束时间,位置和事件名称。我之前从未解析过这种类型的数据。点击API URL并获得响应工作正常,我只需要解析帮助。
我尝试过这些解决方案,但它没有用。
JsonArray
和JSON对象有两个键和值?JSON:
[
{
"end": {
"endDate": "2018-03-09",
"endTime": "03:00",
"_id": "5a901a7d9fee7d156d594b04"
},
"location": "Dance Tent",
"start": {
"startDate": "2018-03-09",
"startTime": "02:00",
"_id": "5a901a7d9fee7d156d594b05"
},
"announcementName": "Jumanji Dance Party"
}
]
代码:
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
String fullName = jsonObject.getString("startTime");
String about = jsonObject.getString("announcementName");
String artistType = jsonObject.getString("endTime");
String link = jsonObject.getString("location");
//String avatar = jsonObject.getString("avatar");
Annoucement_Day_One artistInfoGetter=new Annoucement_Day_One( fullName,about, artistType, link );
annoucementDayOneList.add(artistInfoGetter);
wednesdayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("ERRROR RES: ", error.toString());
myInstance.dismiss();
}
});
requestQueue.add(jsonArrayRequest);
答案 0 :(得分:2)
ArrayList<Holder1> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
for(int index = 0 ;index < jsonArray.length() ; index++){
JSONObject jsonObject1 = jsonArray.getJSONObject(index);
//make a holder for end, location, start,announcementName
Holder1 holder = new Holder1();
holder.setLocation(jsonObject1.optString("location"));
holder.setAnnouncementName(jsonObject1.optString("announcementName"));
//------------
JSONObject jsonObjectEnd =jsonObject1.getJSONObject("end");
holder.setEndDate(jsonObjectEnd.optString("endDate"));
holder.setEndTime(jsonObjectEnd.optString("endTime"));
holder.setEndID(jsonObjectEnd.optString("_id"));
//--------------
JSONObject jsonObjectStart =jsonObject1.getJSONObject("start");
holder.setStartDate(jsonObjectStart.optString("startDate"));
holder.setStartTime(jsonObjectStart.optString("startTime"));
holder.setStartID(jsonObjectStart.optString("_id"));
//--------------
arrayList.add(holder);
}
} catch (JSONException e) {
e.printStackTrace();
}
接受答案。如果你喜欢我写的方式。