将JSON数组响应转换为Java中的数组以显示android中的按钮

时间:2015-08-29 11:45:12

标签: java android arrays json

我的webservices有以下JSON响应

{"error":"false","subjects":[{"subject":"1. Finance"},{"subject":"2. Eco"},{"subject":"3. Comm"},{"subject":"4. MGM"},{"subject":"5.  Basic Computer Skills"},{"subject":"6. Buss Env"},{"subject":"7. Intro to finances"}]}

我只想选择要返回的主题并将其存储在数组中。

然后,数组将用于填充我在Android活动中创建的按钮列表的文本,默认情况下可见性设置为已消失。

对此的任何帮助将不胜感激

由于

3 个答案:

答案 0 :(得分:0)

一种简单的方法是使用GSon库,它允许轻松解析JSON:

例如:

 public class Result {
    public boolean error;
    public ArrayList<Subject> subjects;
 }

 public class Subject {
    public String subject;
 }

然后,代码中的其他地方:

Gson gson = new Gson();
Result result = gson.fromJson(yourJsonString, Result.class);
ArrayList<Subject> yourSubjects = result.subjects;

请注意,Gson需要有权访问您的属性。避免使用public,更好地定义getter / setter。 更多关于Gson的信息:

https://sites.google.com/site/gson/gson-user-guide

答案 1 :(得分:0)

为您的例子:

{"error":"false","subjects":[{"subject":"1. Finance"},{"subject":"2. Eco"},{"subject":"3. Comm"},{"subject":"4. MGM"},{"subject":"5.  Basic Computer Skills"},{"subject":"6. Buss Env"},{"subject":"7. Intro to finances"}]}

您可以使用JSONArray执行此操作:

JSONObject myjson = new JSONObject(the_json_you_got);
JSONArray the_json_array = myjson.getJSONArray("subjects");

返回数组对象。

然后你可以像这样迭代:

int len = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
    JSONObject another_json_object = the_json_array.getJSONObject(i);

    arrays.add(another_json_object);
}


JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

答案 2 :(得分:0)

使用JSONObjectJSONArray

JSONObject data = new JSONObject(jsonString);
JSONArray subjects = data.getJSONArray("subjects");
String[] subjectsArray = new String[subjects.length()];
for(int i = 0; i < subjects.length(); i++){
     subjectsArray[i] = subjects.getString("subject");
}