有时候,写接口的时候,需要传好多属性,往往以json数据的格式传递到后台,下面就来举一个我写的接口,主要是用来说明咋解析数据获得需要的字段
首先,前端传递的wordsJson数据是这样的:
{
"uid":"32854",
"IDCode":"000066",
"wordsJson":[ { "dayNum":"7", "name":"Tizhong" }, { "dayNum":"5", "name":"BloodPressure" }, { "startTime":"2019-07-06", "dayNum":"7", "name":"buNum", "endTime":"2019-07-12" }, { "dayNum":"7", "name":"MealBloodSugar" } ],
"words":"Tizhong,BloodPressure,buNum,MealBloodSugar"
}
后台如何解析穿度过来的这个json 字段:
拿到该字段转换为json:
public void newUserbodyInfo(HttpServletResponse response,String json){ response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods","POST"); response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type"); if (StringUtils.isEmpty(json)){ CommonUtil.renderJson(response,MapUtil.setRequestCode(ResultCode.ERROR.getCode(),"",ResultCode.ILLEGAL_REQUEST_ARGUMENT.getDesc())); return; } JSONObject jsonObject = JSONObject.fromObject(json); //拿到传递来的值: String wordsJson = jsonObject.getString("wordsJson"); if (StringUtils.isEmpty(wordsJson)){ System.out.printIn("wordsJson不能为空!")); }else{ JSONArray jsonArray=JSONArray.fromObject(wordsJson); for (int i = 0; i < jsonArray.size(); i++) { Map map = (Map) jsonArray.get(i); String num=map.get("dayNum").toString(); String number= map.get("name").toString(); System.out.println(number+"==="+num); }
}
}
JSONArray jsonArray=JSONArray.fromObject(wordsJson);将获得String 转为 json数组,然后循环着个格式获得数据。 2.另外一种: 获得json格式是data: { "body":[ { "tid":"24", "tName":"协和血糖专家小组招募计划", "date":[ { "num":"5", "tid":"0", "type":"24" }, { "num":"1", "tid":"1", "type":"24" }, { "num":"1", "tid":"2", "type":"24" } ] } ], "IOS_VERSION_CODE":"1000000", "IOS_VERSION":"1.0", "status":"1", "ANDROID_VERSION_CODE":"1020006", "ANDROID_VERSION":"1.2.6", "msg":"" } 解析的话:
JSONObject jsonObject = JSONObject.fromObject(data);if (jsonObject.getInt("status") == 1){ List list1 = (List) jsonObject.get("body"); Map map = (Map) list1.get(0); List resultList = new ArrayList();}
List list1 = (List) jsonObject.get("body");是将获得json中获取有用的body的数据,如下红线的地方。
Map map = (Map) list1.get(0);则是将body中的数据转为一个Map 接着就可以去Map中的值了。 这只是我用的json格式的数据,不一样的传递不一样、