json解析时自动判断是object还是array
来源:互联网 发布:cf淘宝网 黄金套装 编辑:程序博客网 时间:2024/05/16 07:27
参考:
jsonObject.getString()解析任意字段均可强转为string
json解析时自动判断是object还是array
解析json时遇到的问题,返回的json内容中可能为jsonArray,也可能是jsonObject,
当只有一个信息时是jsonObject,有多个信息时是jsonArray,如果去修改json的返回格式有些不现实。通过字符判断的话又很麻烦。
{“scm”:{“key1”:”vlaue1”,”key2”:”vlaue2”}}
{“scm”:[{“key1”:”vlaue1”,”key2”:”vlaue2”},{“key11”:”vlaue11”,”key22”:”vlaue22”}]}
解决方案:通过JSONTokener解析,JSONTokener在解析过程中可以自动转换为对应的类型
jsonObject.getString()解析任意字段均可强转为string
使用 JSONTokener的JSONTokener.nextValue() 会给出一个对象,然后可以动态的转换为适当的类型。
String jsonStr = "...."; //json字符串 Object json = new JSONTokener(jsonStr).nextValue(); if(json instanceof JSONObject){ JSONObject jsonObject = (JSONObject)json; //further actions on jsonObjects //... }else if (json instanceof JSONArray){ JSONArray jsonArray = (JSONArray)json; //further actions on jsonArray //... }
示例:
if (jsonObject.has("data")) { Object listArray = new JSONTokener(jsonObject.getString("data")).nextValue(); if (listArray instanceof JSONObject){ JSONObject dataJsonObject = (JSONObject)listArray; model.data = dataJsonObject; if (dataJsonObject.has("token")) { model.token = dataJsonObject.getString("token"); } }}
阅读全文
0 0
- json解析时自动判断是object还是array
- json解析时自动判断是object还是array
- Javascript中判断变量是 array还是object(是数组还是对象)
- 判断json是jsonobject还是jsonarray
- 怎么判断一个object是否是数组(array)?
- 怎样判断JSON数据类型是JSONObjec还是JSONArray
- 使用存储过程自动判断是添加还是修改
- 判断程序是自动启动还是用户启动
- 自动判断是否是手机端浏览还是电脑…
- PHP自动判断字符串是gb2312还是utf8编码
- 字符串 object (json)object array 转换
- php的老兄传给客户端[object object]数据如何解析,但他坚称是json...
- php stdClass Object转array array解析
- jquery ajax获取json并解析,获取的json是object对象格式
- 应用alert 判断json还是json字符串
- Object,Map,List,Array转为Json格式
- 判断是手机还是PC
- 判断是iPhone还是iPad
- 百度地图_ 基础地图的使用
- Gitlab hook设置
- Linux下无法使用add-apt-repository命令
- json格式,ajax报错
- 自增主键的返回
- json解析时自动判断是object还是array
- AutoResetEvent
- Spring Boot Web 开发注解篇
- 微信小程序--cover-view
- 项目素材
- BeanUtil.beanCopy
- java多线程
- 变量、作用域问题
- C语言函数一本道来