Android开发将List转化为JsonArray和JsonObject

客户端需要将List<Object>转化为JsonArray和JsonObject的方法:

首先,List中的Object的属性需要是public:

class Person
{
public String name;
public String sex;
public int age;
}

下面假设有List<Person> personList = new ArrayList<Person>(); 中已经装载好了数据:

JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
JSONObject tmpObj = null;
int count = personList.size();
for(int i = ; i < count; i++)
{
tmpObj = new JSONObject();
tmpObj.put("name" , personList.get(i).name);
tmpObj.put("sex", personList.get(i).sex);
tmpObj.put("age", personList.get(i).age);
jsonArray.put(tmpObj);
tmpObj = null;
}
String personInfos = jsonArray.toString(); // 将JSONArray转换得到String
jsonObject.put("personInfos" , personInfos); // 获得JSONObject的String

jsonArray转换的String如下:

[{"name": "mxd", "sex": "boy", "age": }, {"name": "Tom", "sex": "boy", "age": }, {"name": "Jim", "sex": "girl", "age": }]

jsonObject转化的String如下:

{"personInfos": [{"name": "mxd", "sex": "boy", "age": }, {"name": "Tom", "sex": "boy", "age": }, {"name": "Jim", "sex": "girl", "age": }]}
上一篇:HDU 1863


下一篇:sqlserver中批量导出所有作业或链接脚本