Android开发将List转化为JsonArray和JsonObject
2016-07-19 14:40
525 查看
客户端需要将List<Object>转化为JsonArray和JsonObject的方法:
首先,List中的Object的属性需要是public:
下面假设有List<Person> personList = new ArrayList<Person>(); 中已经装载好了数据:
jsonArray转换的String如下:
jsonObject转化的String如下:
首先,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}]}
相关文章推荐
- Object
- 对象(object)和变量(variable)的区别和联系
- PHP简单 对象(object) 与 数组(array) 的转换
- JavaScript Object.prototype.constructor属性详解
- Objective-C(十二、快速枚举,枚举器NSEnumerator和集合类NSSet)——iOS开发基础
- object与class的区别
- Attempt to read from field 'int android.view.View.mViewFlags' on a null object reference
- 浅析JavaScript获得Object对象(自定义对象)的类型名方法
- applicatin/x-oleobject
- Java IO流:转化流InputStramReader,数据流DataStream,对象流ObjectStream
- 使用SWFObject嵌入Flash资源
- 线程操作案例--生产者与消费者,Object类对线程的支持
- Objective-C中NSArray类的解读
- Intent 传递List<Object>
- 属性动画之ObjectAnimator
- Effective Object-c 2.0 读书笔记
- php_lang_ref:Classes_and_Objects>>Trait
- Objective-C runtime之运行时的基本特点(三)
- List<Object> 使用Linq
- xmpp配置服务器