0

对不起标题,我解释一下。

我正在开发一个使用 Google App Engine 上的 WebService 的 Android 应用程序。在我的 WebService 中,我通过 JAX-RS 在 JSON 中转换了一个 ArrayList,最终的 JSON 类似于

{“课程”:[{“名称”:“blabla”,“教授”:“汤姆”},{“名称”:“blabla”,“教授”:“汤姆”}]}

这是实用的还是有更好的方法?

然后我从 Android 应用程序中获取这个 JSON 并将其转换为 JSONObject 并使用在线找到的片段:

DefaultHttpClient defaultClient = new DefaultHttpClient();

HttpGet httpGetRequest = 新的 HttpGet(s);

HttpResponse httpResponse = defaultClient.execute(httpGetRequest);

BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

字符串 json = reader.readLine();

JSONObject jsonObject = 新 JSONObject(json);

我怎样才能回到我的 ArrayList?

我已经阅读了大量代码并尝试使用 Gson ......这应该很容易,但我昨天已经失去了一整天......

4

3 回答 3

2
  private class Info {
        public String name;
        public String prof;
    }

    ArrayList<Info> arrayList = new ArrayList<Info>();

    JSONArray array = jsonObject.optJSONArray("lessons");
    int len = array.length();

    for (int i = 0; i < len ; i++) {
     JSONObject tmp = array.optJSONObject(i);
     Info info = new Info();
     info.name = tmp.optString("name");
     info.prof = tmp.optString("prof");
      arrayList.add(info)
}

检查拼写错误

于 2012-04-19T10:25:44.580 回答
0

如果你想使用内置的 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;

希望这可以帮助!

于 2012-04-19T10:33:56.973 回答
0

从这篇文章下载我的例子。一个完整的源代码,展示了如何将对象转换为 json 对象。希望它有所帮助。如何在我的 android 应用程序中保存一组简单对象?

于 2012-04-19T10:15:30.040 回答