[英]Converting ArrayList to JSON - Android
我有一个数组列表和一个单独的字符串。 我想将它们转换为JSON格式,并期望它低于json格式。
预期格式,
{
"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 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;
}
但我同意其他答案,建议你使用像GSON这样的“映射”技术,而不是手工编写。 特别是如果这变得更复杂。
你可以使用GSON。
它提供了许多功能,使用起来非常简单。
看看这些例子。
http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
http://www.techrepublic.com/blog/software-engineer/use-gson-to-work-with-json-in-your-android-apps/
希望这可以帮助。
解析为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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.