zoukankan      html  css  js  c++  java
  • 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}]}
  • 相关阅读:
    bzoj1096: [ZJOI2007]仓库建设
    bzoj3289: Mato的文件管理
    bzoj1878: [SDOI2009]HH的项链
    bzoj1295: [SCOI2009]最长距离
    bzoj1056: [HAOI2008]排名系统 && 1862: [Zjoi2006]GameZ游戏排名系统
    vijosP1026毒药?解药?
    bzoj1293: [SCOI2009]生日礼物
    bzoj1483: [HNOI2009]梦幻布丁
    PCB开窗
    3W原则
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/5684746.html
Copyright © 2011-2022 走看看