Java 将ArrayList转换为JSON-Android
我有一个数组列表和一个单独的字符串。我想把它们转换成JSON格式,并希望它低于JSON格式 预期格式Java 将ArrayList转换为JSON-Android,java,android,json,Java,Android,Json,我有一个数组列表和一个单独的字符串。我想把它们转换成JSON格式,并希望它低于JSON格式 预期格式 { "last_sync_date": "2014-06-30 04:47:45", "recordset": [ { "contact_group": { "guid": "y37845y8y", "name": "Family", "description": "Family
{
"last_sync_date": "2014-06-30 04:47:45",
"recordset": [
{
"contact_group": {
"guid": "y37845y8y",
"name": "Family",
"description": "Family members",
"isDeleted": 0
}
},
{
"contact_group": {
"guid": "gt45tergh4",
"name": "Office",
"description": "Office members",
"isDeleted": 0
}
}
]
}
我用这种方法是错误的
public void createGroupInServer(Activity activity, String lastSyncDateTime, ArrayList<ContactGroup> groups)
throws JSONException {
// create json object to contact group
JSONObject syncDateTime = new JSONObject();
syncDateTime.putOpt("last_sync_date", lastSyncDateTime);
JSONArray jsArray = new JSONArray("recordset");
for (int i=0; i < groups.size(); i++) {
JSONObject adsJsonObject = new JSONObject("contact_group");
adsJsonObject = jsArray.getJSONObject(i);
adsJsonObject.put("guid", groups.get(i).getGroupId());
adsJsonObject.put("name", groups.get(i).getGroupName());
adsJsonObject.put("isDeleted", groups.get(i).getIsDeleted());
}
public void createGroupInServer(活动、字符串lastSyncDateTime、ArrayList组)
抛出JSONException{
//为联系人组创建json对象
JSONObject syncDateTime=新的JSONObject();
putOpt(“上次同步日期”,lastSyncDateTime);
JSONArray jsArray=新的JSONArray(“记录集”);
对于(int i=0;i
请帮助。解析到
JSONArray
JSONArray jsonArray = (JSONArray)new JSONParser().parse(your json string);
为您的代码
JSONObject jsonObject = (JSONObject)new JSONParser().parse(your json string);
JSONArray array = (JSONArray)jsonObject.get("recordset");
你可以用GSON
它提供了很多功能,而且使用非常简单
看看这些例子
希望这能有所帮助。您基本上走在正确的轨道上……但也有一些错误:
public JSONObject createGroupInServer(
Activity activity, String lastSyncDateTime,
ArrayList<ContactGroup> groups)
throws JSONException {
JSONObject jResult = new JSONObject();
jResult.putOpt("last_sync_date", lastSyncDateTime);
JSONArray jArray = new JSONArray();
for (int i = 0; i < groups.size(); i++) {
JSONObject jGroup = new JSONObject();
jGroup.put("guid", groups.get(i).getGroupId());
jGroup.put("name", groups.get(i).getGroupName());
jGroup.put("isDeleted", groups.get(i).getIsDeleted());
// etcetera
JSONObject jOuter = new JSONObject();
jOuter.put("contact_group", jGroup);
jArray.put(jOuter);
}
jResult.put("recordset", jArray);
return jResult;
}
publicjsonobjectcreategroupinserver(
活动活动,字符串lastSyncDateTime,
数组列表组)
抛出JSONException{
JSONObject jResult=新的JSONObject();
jResult.putOpt(“上次同步日期”,lastSyncDateTime);
JSONArray jArray=新的JSONArray();
对于(int i=0;i
但我同意其他建议你使用“映射”的答案像GSON这样的技术,而不是手工编写。特别是如果这变得更复杂的话。你有没有考虑过使用Jackson或GSON来编写更少的bug?如果没有,你应该这样做。上面的任务会很简单。@ZhenxiaoHao-没有。问题显然是关于将Java对象转换为JSON。他提供的JSON显然是为了在示例Java代码生成时。