2015-08-29 23 views
0

我從我的web服務轉換JSON陣列響應Java數組顯示按鈕的Android

{"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"}]} 

以下JSON響應我想只挑返回的對象,並將其存儲在數組中。

然後,該數組將被用於填充我在我的android活動中創建的按鈕列表的文本,這些按鈕的默認設置爲可見。

任何幫助,將不勝感激

感謝

回答

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需要訪問您的屬性。避免使用公共的,更好的定義getters/setters。 更多GSON這裏:

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

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