如果你想使用内置的 JSON 类,你可以这样做:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has("lessons")) {
JSONArray jsonLessons = jsonObject.getJSONArray("lessons");
List<Lesson> lessons = new ArrayList<Lesson>();
for(int i = 0; i < jsonLessons.length(); i++) {
JSONObject jsonLesson = jsonLessons.get(i);
// Use optString instead of get on the next lines if you're not sure
// the fields are always there
String name = jsonLesson.getString("name");
String teacher = jsonLesson.getString("prof");
lessons.add(new Lesson(name, teacher));
}
}
只要确保你的 Json 总是在一行中到达。换行会破坏此代码,因为您只阅读该行。
我的选择是Gson。在这种情况下,您将创建一个课程类和一个计划类:
public class Lesson {
String name;
String prof;
}
public class Schedule {
List<Lesson> lessons;
}
请注意,字段名称对应于 json 字段。如果感觉更好,请随意将字段设为私有并添加一些 getter 方法。:-)
现在您可以解析出包含课程列表的 Schedule 对象:
DefaultHttpClient defaultClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet(s);
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
Reader in = new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8");
Gson gson = new Gson();
Schedule schedule = gson.fromJson(in, Schedule.class);
List<Lesson> lessons = schedule.lessons;
希望这可以帮助!