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"
        }
    ]
    
}

首先导包是需要导入阿里的

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

拿到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 "错误";
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ybbgrain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值