繁体   English   中英

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

[英]Converting JSON array response to array in Java to display buttons in android

我的网络服务有以下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活动中创建的按钮列表的文本,这些按钮的可见性默认情况下设置为“消失”。

任何帮助,将不胜感激

谢谢

一种简单的方法是使用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需要访问您的属性。 避免使用公共的,更好定义的获取器/设置器。 有关Gson的更多信息,请点击此处:

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

例如:

{"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);

使用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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM