从给定的Map到json字符串(或JSONObject)

时间:2012-06-09 20:29:22

标签: java json map

在Java中,我通过post(例如)传递了这些键/值对:

form_id=undefined

frmb[0][cssClass]=input_text

frmb[0][required]=checked

frmb[0][values]=First Name

frmb[1][cssClass]=input_text

frmb[1][required]=checked

frmb[1][values]=Last Name

frmb[2][cssClass]=textarea

frmb[2][required]=undefined

frmb[2][values]=Bio

frmb[3][cssClass]=checkbox

frmb[3][required]=undefined

frmb[3][title]=What's on your pizza?

frmb[3][values][2][baseline]=undefined

frmb[3][values][2][value]=Extra Cheese

frmb[3][values][3][baselise]=undefined

frmb[3][values][3][value]=Pepperoni

frmb[3][values][4][baseline]=undefined

frmb[3][values][4][value]=Beef

frmb[4][cssClass]=radio

frmb[4][required]=undefined

frmb[4][title]=Do you like pizza?

frmb[4][values][2][baseline]=checked

frmb[4][values][2][value]=Yes

frmb[4][values][3][baseline]=undefined

frmb[4][values][3][value]=No

frmb[5][cssClass]=select

frmb[5][multiple]=checked

frmb[5][required]=checked

frmb[5][title]=Select a pizza type:

frmb[5][values][2][baseline]=checked

frmb[5][values][2][value]=Margherita

frmb[5][values][3][baseline]=undefined

frmb[5][values][3][value]=Napoli

frmb[5][values][4][baseline]=undefined

frmb[5][values][4][value]=Marinara

我要创建以下json:

[{"cssClass":"input_text","required":"checked","values":"First Name"},{"cssClass":"input_text","required":"checked","values":"Last Name"},{"cssClass":"textarea","required":"undefined","values":"Bio"},{"cssClass":"checkbox","required":"undefined","title":"What's on your pizza?","values":{"2":{"value":"Extra Cheese","baseline":"undefined"},"3":{"value":"Pepperoni","baseline":"undefined"},"4":{"value":"Beef","baseline":"undefined"}}},{"cssClass":"radio","required":"undefined","title":"Do you like pizza?","values":{"2":{"value":"Yes","baseline":"checked"},"3":{"value":"No","baseline":"undefined"}}},{"cssClass":"select","required":"checked","multiple":"checked","title":"Select a pizza type:","values":{"2":{"value":"Margherita","baseline":"checked"},"3":{"value":"Napoli","baseline":"undefined"},"4":{"value":"Marinara","baseline":"undefined"}}}]

我该怎么办?

我没有成功解析解析密钥,对属于同一个JSONObject的元素进行分组。

3 个答案:

答案 0 :(得分:1)

您可以使用Gson库进行此操作。它不支持嵌套映射的序列化(我假设您的输出表示嵌套映射)。您可以按照this thread

中的说明编写自定义序列化程序/反序列化程序或创建自己的序列化方法

答案 1 :(得分:1)

您可以这样做:

JSONArray jsonItems = new JSONArray();

for (int i = 0; i < frmb.size(); i++) {  

JSONObject json = new JSONObject();  
json.put("cssClass", frmb[i][cssClass]);  
json.put("required",frmb[i][required]);  
//put json object to json array  
jsonItems.put(json);   
}

查看here了解详情

答案 2 :(得分:0)

我通过解析密钥并使用两个临时哈希表构建JSONObjects来解决。