java解析json格式的数据

java中没有内置的JSON的解析,因此需要借助到第三方的类库。

常用的JSON解析类库有:

Gson:谷歌的json库,功能很全面

FastJson:阿里巴巴的json库,性能很优秀

JackJson:社区很活跃更新速度也很快

 

  • 环境配置

在maven构建的项目中,在pom.xml文件中添加fastjson依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>
  • 解析

将json格式的字符串转换为JSONObject对象,然后使用jsonObject对象的内置方法,就获取到json中某个字段的值了,根据json中你想要获取的数据的类型可以采用不同的方法。

如:获取一个数据类型是字符串的字段值,用:jsonObject.getString();

获取一个数据类型是数组的字段值,用:jsonObject.getJSONArray();

获取一个数据类型是布尔型的字段值,用:jsonObject.getBoolean();

当想要获取的字段,嵌套的层级很深的话,就需要一层一层的解析。

以下是一个解析Json格式的字符串的示例:

{
	"code": 0,
	"data": {
		"totalPages": 2,
		"totalElements": 115,
		"content": [{
				"name": "828",
				"year": 2018,
				"state": false,
				"count":"12"
			}, {
				"name": "828",
				"year": 2018,
				"state": false,
				"count":"22"
			}
		],
		"end": false
	},
	"result": false
}

需求是:获取content数组下所有的count字段值,并计算合计

@Test
public void JsonParing(){
    // 1、读取保存在本地的文件,获取到json格式的字符串数据
    String filePath = "D:\\file\\jsonData.json";
    String jsonString = ReadJsonFile(filePath);

    // 2、将字符串转换为JSONObject对象
    JSONObject jsonObject = JSONObject.parseObject(jsonString);
    // 3、获取data字段对应的值(还是一个json格式的数据)
    String data = jsonObject.getString("data");
    
   // 4、data还是一个json格式的字符串,需要在转换成JSONObject对象
   JSONObject dataObj = JSONObject.parseObject(data);
   // 5、获取content数组
   JSONArray contentArr = dataObj.getJSONArray("content");
   int count = 0;
   // 6、遍历JSONArray中的每个数组,你到count字段值,参加计算得到合计
   for(int i=0;i<contentArr.size();i++){
       // 7、JSONArray中的每个数组还是一个JSONObject对象
       JSONObject itemObject = contentArr.getJSONObject(i);
       count += Integer.parseInt(itemObject.getString("count"));
   }
   System.out.println(count);
}

/**
 * 读取文件
 * @param fileName  文件的路径
 * @return
 */
public static String ReadJsonFile(String fileName) {
    String jsonStr = "";
    FileReader fileReader = null;
    Reader reader = null;
    try {
        File jsonFile = new File(fileName);
        fileReader = new FileReader(jsonFile);

        reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        jsonStr = sb.toString();
        return jsonStr;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }finally {
        try{
            if(fileReader != null){
                fileReader.close();
            }
            if(reader != null){
                reader.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

执行上述代码得到的结果是:34

使用fastjson解析json数据,最重要的就是能正确判断每层解析的数据类型,并数量使用JSONObject 和 JSONArray之间的转换

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值