java中JSONObject与JSONArray的使用
JSONObject与JSONArray
最近在学习过程中用到了稍微复杂点的json数据需要将json数据解析出来,这里就截取一部分作为例子
1.JSONObject介绍
JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。
2.下载jar包
http://files.cnblogs.com/java-pan/lib.rar
*或者在Maven的pom.xml文件中直接配置如下:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
json数据:
{
"cartypes":[
{"id":1,"imgUrl":"img/l.jpg","bigimg": "img/d.jpg","title":"别克威朗","marketprice":"15.29","periods":"12",
"endrepayone":"96800","endrepaytwo":"96800","endrepaythree":"93000",
"endmonthone":"3408","endmonthtwo":"3408","endmonththree":"3278",
"repayfirst":"15290","repaytwo":"22935", "repaythree":"30580",
"monthrepayone":"3578","monthrepaytwo":"2878","monthrepaythree":"2478",
"cardetails":
[{
"imageId00": "img/first-bkwl.jpg",
"imageId01": "img/bkwl01.jpg",
"imageId02": "img/bkwl02.jpg",
"imageId03": "img/bkwl03.jpg",
"imageId04": "img/bkwl04.jpg",
"carname": "别克",
"carmatter": "威朗",
"carvolume":"1.5L",
"sitnum":"5",
"cargearbox":"6挡手自一体",
"caremission":"国V",
"carldone":"一体式座舱",
"carldtwo":"绒面内饰",
"carldthree":"全景天窗",
"carldfour":"展翼型HID大灯"
}]
},
{"id":2,"imgUrl":"img/l.jpg","bigimg": "img/d.jpg","title":"英菲尼迪","marketprice":"18.98","periods":"12",
"endrepayone":"126800","endrepaytwo":"126800","endrepaythree":"126800",
"endmonthone":"4458","endmonthtwo":"4458","endmonththree":"4458",
"repayfirst":"18980","repaytwo":"28470", "repaythree":"37960",
"monthrepayone":"2738","monthrepaytwo":"1878","monthrepaythree":"998",
"cardetails":
[{
"imageId00": "img/first.jpg",
"imageId01": "img/yfnd01.jpg",
"imageId02": "img/yfnd02.jpg",
"imageId03": "img/yfnd03.jpg",
"imageId04": "img/yfnd04.jpg",
"carname": "英菲尼迪",
"carmatter": "ESQ",
"carvolume":"1.6L",
"sitnum":"5",
"cargearbox":"CVT无级变速",
"caremission":"国V",
"carldone":"定制轮毂",
"carldtwo":"多功能方向盘",
"carldthree":"LED尾灯",
"carldfour":"真皮座椅"
}]
}
]
}
当接受到的是上面的json数据时,要获取到里面的键对应的值应该怎样做呢,比如要获取title的值,获取cardetails中的imageId02的值等。
面对这样数组与对象相互嵌套的情况需要一步步将数据拆分,主要思想还是根据键取值,对于数组类型还是需要先根据”下标”取出元素。这里还需要用到JSONObject与JSONArray。
将上面的json数据简化就是:(这里保留个id便于识别)
{
"cartypes":[
{
"id":1,"bigimg": "img/dt-bkwl.jpg",
"cardetails": [{ "imageId02": "img/bkwl02.jpg}]
}
{
"id":2,"bigimg": "img/xxx.jpg",
"cardetails":[{"imageId002":"img/xx.jpg"}]
}
]
}
这就是简化了的json数据,可以看出这个串最外层是一个大的键为cartypes的对象,而它的值是json数组形式的比较复杂的json数据。继续分析 [ ]的部分,可以看到,里面有两个数组元素,每个元素分别是被{ }包起来的json对象,他们的元素组成相同,再看每个元素里面包含几个键值对的数据,其中键cardetails的值又是一个嵌套的json数组,里面包含一个json对象。分析完毕。那该怎样才能(拿到数据)解析呢?
使用JSONObject与JSONArray
一般取数据有两种方式,看需要选择。
方式①:
通过 JSONObject.getString("键")直接获取,这种方式只能每次获取一个。
方式②
通过构建与json对象相应的bean来获取。
我在写上面的例子时用到了两种方式,由于需要使用到 id,bigimg以及cardetails中的大部分数据,因此我在使用时将cardetails封装成一个bean,方便使用,而其他用到的比较少,因此就直接根据键获取值。
另外需要注意的是,JSONObject,JSONArray分别对应的是json数据的两种格式。即{"张三" : "男"} , [{ 张三" : " 男" }] ,使用时需要将其转换成对应的对象。
如(示例):
JSONObject jsonObject = JSONObject.fromObject(json); //将json字符串转换为JSONObject
JSONArray jsonArray = JSONArray.fromObject(json); //将json字符串转换为JSONArray
还有一点需要指出:在取键值是始终需要根据键取值,从外到内,取内层的键的值需要先获取外层键的值,如果跨越取值会报错。
下面演示取值:
JSONObject jsonObject = JSONObject.fromObject(json); //将json字符串转化为JSONObject
String cartypes=jsonObject.getString("cartypes"); //通过getString("cartypes")取出里面的信息
JSONArray jsonArray = JSONArray.fromObject(cartypes); //将取到的cartypes对应的(一组)值字符串转换为JSONArray
String id= job.getString("id"); //取id
String bigImg = job.getString("bigimg"); //大图
System.out.println("bigImg:"+bigImg); //可以显示已经拿到bigimg的值
由于cardetails下的基本都是需要的值,一个一个取值比较麻烦,因此将cardetails封装成一个bean 如下:
Cardetails.java
public class Cardetails {
private String imageId00;
private String imageId01;
private String imageId02;
private String imageId03;
private String imageId04;
private String carname;
private String carmatter;
private String carvolume;
private int sitnum;
private String cargearbox;
private String caremission;
private String carldone;
private String carldtwo;
private String carldthree;
private String carldfour;
//get set 方法以及toString方法略
}
到这里,需要将cardetails中的键全转成Cardetails中的属性,方法如下:
//将cardetail封装成bean
JSONArray carDetailArr=job.getJSONArray("cardetails");//将json字符串转化为JSONArray
JSONObject carDetailObj = carDetailArr.getJSONObject(0);//获取数组第一个元素
Cardetails cardetails = (Cardetails) JSONObject.toBean(carDetailObj, Cardetails.class);//封装成bean
System.out.println("cardetails:"+cardetails); //能获取到数据
最后附上部分代码:
public void getICarDetail(int id){
String json=null;
try {
json=iCarDetail.getICarDetail(id);//这里既是获取上面json数据
} catch (Exception e) {
e.printStackTrace();
}
int jsonId=0;//json数组里的id值
JSONObject jsonObject = JSONObject.fromObject(json); //将json字符串转化为JSONObject
String cartypes=jsonObject.getString("cartypes");//通过getString("cartypes")取出里面的信息
JSONArray jsonArray = JSONArray.fromObject(cartypes); //将取到的cartypes对应的(一组)值字符串转换为JSONArray
//遍历jsonarray 数组
if(jsonArray.size()>0){
for(int i=0;i<jsonArray.size();i++){
JSONObject job = jsonArray.getJSONObject(i);//把每一个对象转成json对象
jsonId=(int)job.get("id"); //得到每个对象中的id值
if(jsonId==id){
//获取相关值
String title = job.getString("title");
String bigImg = job.getString("bigimg");
String repayFirst = job.getString("repayfirst");
String endrepayone = job.getString("endrepayone");
String endmonthone = job.getString("endmonthone");
String marketprice = job.getString("marketprice");
//将cardetail封装成bean
JSONArray carDetailArr=job.getJSONArray("cardetails");//将json字符串转化为JSONArray
JSONObject carDetailObj = carDetailArr.getJSONObject(0);//获取数组第一个元素
Cardetails cardetails = (Cardetails) JSONObject.toBean(carDetailObj, Cardetails.class);//封装成bean
//输出显示
System.out.println("******************");
System.out.println("jsonId:"+jsonId);
System.out.println("title:"+title);
System.out.println("bigImg:"+bigImg);
System.out.println("repayFirst:"+repayFirst);
System.out.println("endrepayone:"+endrepayone);
System.out.println("endmonthone:"+endmonthone);
System.out.println("marketprice:"+marketprice);
System.out.println("cardetails:"+cardetails);
}
java中JSONObject与JSONArray的使用的更多相关文章
- [转]java中JSONObject与JSONArray的使用详细说明及有关JSON的工具类
JSONObject与JSONArray的使用 一.JAR包简介 要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包: 1.commons-lang.jar 2.c ...
- Java中JSONObject相关操作
maven项目pom配置: <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>js ...
- [fastjson] - fastjson中 JSONObject 和 JSONArray
/** * 对jsonObject对象进行key的获取 * @param jsonObject */ public ArrayList<String> jsonKeyRecursion(J ...
- JavaScript中JSONObject和JSONArray相关知识备忘(网络转载)
1.json的格式,有两种: {"key": "value"} //JSONObject(对象) [{"key1": "value ...
- java判断jsonObject和jsonArray是否为空
resJsonObj = {"res":"0","msg":"","data":{"Nam ...
- java中转换json方式(JSONArray,JSONObject),json解析
package com.yunos.tv.video.resource.controller.web; import java.util.ArrayList; import java.util.Has ...
- java和js中JSONObject,JSONArray,Map,String之间转换
--------------------------------------------------Java中--------------------------------------------- ...
- Java学习笔记50:JSONObject与JSONArray的使用
Java不像PHP解析和生产JSON总是一个比较痛苦的过程.但是使用JSONObject和JSONArray会让整个过程相对舒服一些. 需要依赖的包:commons-lang.jar commons- ...
- Java之JSON处理(JSONObject、JSONArray)
依赖包:json-20180130.jar MAVEN地址: <dependency> <groupId>org.json</groupId> <artifa ...
随机推荐
- JS 创建长度为100的数组,数值为角标
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 【C++ OpenGL ES 2.0编程笔记】8: 使用VBO和IBO绘制立方体 【转】
http://blog.csdn.net/kesalin/article/details/8351935 前言 本文介绍了OpenGL ES 2.0 中的顶点缓冲对象(VBO: Vertex Buff ...
- 【AS3 Coder】任务九:游戏新手引导的制作原理(下)
在上一篇教程中,我们了解了一套我自创的新手引导管理框架的使用原理,那么在本篇教程中,我们将考虑新手引导制作中可能遇到的一些棘手问题及探讨其解决方案.Are you ready my baby? Let ...
- [Flutter] Creating & Updating State in a Flutter Application
To create a Stateful widget: 1. Create a StatefulWidget 2. Create a State class SGreeting extends St ...
- jquery 中attr和prop的区别
在jQuery API中也有专门解释: Attributes VS. Properties 在一些特殊的情况下,attributes和properties的区别非常大.在jQuery1.6之前,.at ...
- 倍福TwinCAT(贝福Beckhoff)常见问题(FAQ)-人机界面如何设置页面跳转
TC3中,可以点击某个按钮,改变所显示的视图,然后从你写好的页面中选择一个要跳过去的页面 当然,在跳过去的页面上再做一个按钮可以跳回主页面也是必须的 更多教学视频和资料下载,欢迎关注以下信 ...
- Vue工程模板文件 webpack打包
1.github github地址:https://github.com/MengFangui/VueProjectTemplate 2.webpack配置 (1)基础配置webpack.base.c ...
- Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.cache.ehcache.EhCacheRegionFactory] as strategy [org.hibernate.cache.spi.RegionFac
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springfram ...
- Cannot find module 'webpack'
执行webpack命令报错 Error: Cannot find module 'webpack' at Function.Module._resolveFilename (module.js:325 ...
- 解析式/推导式, 生成器 datetime 内建函数
列表解析式(List Comprehension) 语法: [返回值 for 元素 in 可迭代对象 if 条件] 使用中括号[],内部是for循环,if条件可选. 返回一个新的列表. 列表解析式的作 ...