Android development converts List to JsonArray and JsonObject

The client needs to convert List<Object> to JsonArray and JsonObject:

First, the properties of the Object in the List need to be public:

 

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

 

The following assumes that there is List<Person> personList = new ArrayList<Person>(); The data has been loaded in:

 

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

 

The String converted by jsonArray is as follows:

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

The String converted by jsonObject is as follows:

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

Guess you like

Origin blog.csdn.net/qq_26467207/article/details/82665621