我有一个数组列表和一个单独的字符串。我想将它们转换为 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 这样的“映射”技术,而不是手动编码。特别是如果事情变得更复杂的话。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)