栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA解析JSON格式的数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA解析JSON格式的数据

题记

需求是前端传递过来的一个,JSON格式的信息,包含如id,name,age等,要从中解析出某一个字段的值。

实例JSON 

如下JSON字符串需要解析,首先需要找到data这个数组,然后在分别遍历里面的数据。

 具体实例

可以以写死的实例,也可以通过body中传递。

String countrys = "{n" +
                "    "data": [n" +
                "        {n" +
                "            "countryId": "1",n" +
                "            "countryName": "中国",n" +
                "            "countryFullName": "中华人民共和国",n" +
                "            "tenantKey": "TVWYLC4E93"n" +
                "        },n" +
                "        {n" +
                "            "countryId": "4",n" +
                "            "countryName": "韩国",n" +
                "            "countryFullName": "韩国",n" +
                "            "tenantKey": "TVWYLC4E93"n" +
                "        }n" +
                "    ]n" +
                "}";

postman当中body传递的格式

{
   "data": [
        {
            "countryId": "17",
            "countryName": "测试www"
        }
    ]
    
}

 拿到JSON字符串

JSonObject jo =  JSONObject.parseObject(countrys);

具体定位JSON字符串当中的哪一个数组(本次定位data数组)

JSonArray jsonArray = jo.getJSonArray("data");

再遍历JSON字符串的长度,挨个填写要取出的字段,这里获取的是countryId

 for(int i = 0 ; i < jsonArray.size() ; i++){
 JSonObject jsonArrayObjectItem = JSONObject.parseObject(jsonArray.get(i).toString());
                String id = jsonArrayObjectItem.getString("countryId");
                String isArchive = jsonArrayObjectItem.getString("countryIsArchive");
}

 然后久解析出了JSON字符串当中的,countryId字段了。

全部代码
@RequestMapping("/sealedCountry")
    public WeaResult sealedCountry(@RequestBody String countrys){
        try {
            //拿json字符串
            JSonObject jo =  JSONObject.parseObject(countrys);
            //拿具体的那个数组
            JSonArray jsonArray = jo.getJSonArray("data");

            for(int i = 0 ; i < jsonArray.size() ; i++){
                JSonObject jsonArrayObjectItem = JSONObject.parseObject(jsonArray.get(i).toString());
                String id = jsonArrayObjectItem.getString("countryId");
            }
            return "解析成功";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "错误";
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/631313.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号