实例JSON需求是前端传递过来的一个,JSON格式的信息,包含如id,name,age等,要从中解析出某一个字段的值。
如下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 "错误";
}



