如何解析JSON数组并存储在java中的arraylist?

问题描述:

我想解析下面的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

像这样的东西?

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

下面的东西应该为您的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