如何将服务器或网站中的JSON解析为Android Studio中的ListView
>
例如,解析此JSON文件
{
"courses":[
{
"id":1,
"course":"Русский язык"
},
{
"id":2,
"course":"English language"
},
{
"id":3,
"course":"Spanish language"
}
]
}
答案 0 :(得分:0)
您可以分两步完成:
1)创建id,course
的对象列表try {
// Convert the String to JSON
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jArray = jsonObject.getJSONArray("courses");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String id = jObject.getString("id");
String course = jObject.getString("course");
yourList.add(new Course(id, course))
}
} catch (JSONException e) {
Log.e(this.getClass().getName(), "Some JSON error occurred" + e.getMessage());
}
2)编写适配器以将列表转换为ListView
private class MyAdapter extends BaseAdapter {
// override other abstract methods here
@Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
}
((TextView) convertView.findViewById(android.R.id.course))
.setText(getItem(position));
return convertView;
}
}
获取帮助