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 = 0; 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": 12}, {"name": "Tom", "sex": "boy", "age": 23}, {"name": "Jim", "sex": "girl", "age": 20}]

jsonObject转化的String如下:

{"personInfos": [{"name": "mxd", "sex": "boy", "age": 12}, {"name": "Tom", "sex": "boy", "age": 23}, {"name": "Jim", "sex": "girl", "age": 20}]}

猜你喜欢

转载自blog.csdn.net/qq_26467207/article/details/82665621