Android小问题:String转换Json,以及org.json.JSONObject与org.json.JSONArray相互添加
来源:互联网 发布:二维码解码器软件 编辑:程序博客网 时间:2024/05/18 11:26
import org.json.JSONArray;
import org.json.JSONException;import org.json.JSONObject;
这是Android原生的Json数据解析包,虽然没有Gson和fastjson好用。
不过它很轻量,并不需要添加别的jar包,可以为应用节省下小部分空间,利弊各有。
项目中有很多跟js进行交互的地方,传递数据时发现根本无法使用Object跟List<T>,于是就想到了Json。
Android跟js都把数据转换成Json字符串,传递后再各自进行解析。
查了些资料,觉得有几个地方还挺值得记录一下。
解析Json就不再多言,遍地都是,随便查查就能明白,我要说的是数据转换成Json。
1、把对象转换成Json字符串。
2、把字符数组转换成Json字符串。
3、把Object数组转换成Json字符串。
4、在JSONObject中添加Array。
1、把对象转换成Json字符串
JSONObject jsonObject = new JSONObject();jsonObject.put("id", obj.getId());jsonObject.put("url", obj.getUrl());jsonObject.toString();
2、把字符数组转换成Json字符串。
JSONArray jsonArray = new JSONArray();jsonArray.put(string[0]);jsonArray.put(string[1]);jsonArray.put(string[2]);jsonArray.toString();
3、把Object数组转换成Json字符串。
JSONArray jsonArray = new JSONArray(); JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("id", obj.getId()); jsonObject1.put("url", obj.getUrl()); JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("id", obj.getId()); jsonObject2.put("url", obj.getUrl());jsonArray.put(jsonObject);jsonArray.toString();
4、在JSONObject中添加Array。
JSONObject jsonObject = new JSONObject();JSONArray jsonArray = new JSONArray(); JSONObject obj = new JSONObject(); obj.put("id", obj.getId()); obj.put("url", obj.getUrl()); jsonArray.put(obj);jsonObject.put("array", jsonArray);jsonObject.toString();
不过再怎么复杂也都是几种情况相符组合一下而已。
祝君代码永无BUG!!!
1 0
- Android小问题:String转换Json,以及org.json.JSONObject与org.json.JSONArray相互添加
- org.json.simple JSONArray JSONObject
- Java json处理(org.json.JSONObject/org.json.JSONArray)
- org.json.JSONArray#remove
- jsonobject 遍历 org.json.JSONObject
- jsonobject 遍历 org.json.JSONObject
- jsonobject 遍历 org.json.JSONObject
- jsonobject 遍历 org.json.JSONObject
- String转Json,jsonArray,jsonObject
- String转换成json格式(二):org.codehaus.jettison.json.JSONObject
- org.json.JSONObject将对象转换成json
- org.json.JSONObject对象转json,json新增元素,根据json的key获取值。以及list对象格式字符串转jsonArray
- 关于org.json.JSONArray构造JSONArray的问题
- org.json源码分析及增强(一)——JSONObject对象与Java对象相互转换
- Android原生json类org.json.JSONObject初步使用
- org.json.JSONObject中list转json
- 关于Json解析(org.json.JSONObject)
- 关于json字符串以及JSONArray以及JSONObject
- 将指定文件夹下文件及子文件夹下的文件复制到同一级目录
- FPGA 按键控制数码管
- 结构型模式7之1-Proxy代理模式例子理解
- Prim Dijkstra 区别
- centos 7 dns 依赖
- Android小问题:String转换Json,以及org.json.JSONObject与org.json.JSONArray相互添加
- JAVA正则表达式:Pattern类和Mathcer类详解
- hdu 5547 Sudoku【dfs】
- linux之待机流程
- build and install everything into local directory
- Docker背后的容器管理——Libcontainer深度解析
- The device that was selected before performing this action was disconnected or has encountered a pro
- 内核与用户空间的接口procfs, sysctl, ioctl,netlink
- Intellij 家族IDE 修改变量字段快捷方式