2013-03-18 76 views
-1

我想解析下面的JSON數組並存儲在數組列表中。如何解析JSON數組並存儲在java中的arraylist?

[{"type":{"Male":"1","Female":"2"}}] 

我曾嘗試下面的代碼

JSONObject object=getJSONObject(0).getString("type"); 

結果:

{"Male":"1","Female":"2"} 

這裏型是關鍵,其他都值。

它帶有逗號,引號。如何存儲這個值在ArrayList

+1

在'ArrayList'中?你的意思是'Map'嗎? – Keppil 2013-03-18 14:25:33

+0

@感謝kepil.yes.because因爲我想存儲男性值和1值。所以更好的地圖會有幫助 – Ami 2013-03-18 14:29:54

+0

請參閱[this](https://sites.google.com/site/gson/gson-user-guide #TOC-Primitives-Examples)..你將能夠理解整個事物。 – Anubhab 2013-03-18 14:29:41

回答

0

像這樣的東西?

ArrayList<String> list = new ArrayList<String>();  

if (jsonArray != null) {   //In this case jsonArray is your JSON array 
    int len = jsonArray.length(); 
    for (int i=0;i<len;i++){ 
     list.add(jsonArray.get(i).toString()); 
    } 
} 
+0

什麼是jsonObject? – Ami 2013-03-18 14:35:21

+0

我更新了代碼。 – StackFlower 2013-03-18 14:44:00

+0

@ thanks.It返回{「男」:「1」,「女」:「2」}整個部分。如何刪除para-this,逗號,引號? – Ami 2013-03-18 14:55:32

1

下面的東西應該爲您的JSON做訣竅。看到你的JSON我沒有在任何地方看到數組。

String resultJson; // Assuming this has the JSON given in the question. 
JSONObject object = new JSONObject(resultJson); 
JSONObject type = object.getJSONObject("type"); //Get the type object. 

HashMap<String, Integer> map = new HashMap<String, Integer>(); //Creating the Map 

String male = type.getString("male"); //Get the male value 
String female = type.getString("female"); //Get the female value 

map.put("male", Integer.parseInt(male)); 
map.put("female", Integer.parseInt(female)); 
+0

no.dont使用男性和女性作爲key.because基於類型值它可以改變,所以只鍵入靜態。 – Ami 2013-03-18 14:37:11

+0

你可以根據你的需要改變它。我剛剛給出了一個示例代碼片段。 – SudoRahul 2013-03-18 14:39:03