时间:2022-11-27 10:22:58 | 栏目:JAVA代码 | 点击:次
{ "list": [ "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}", "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}", "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}", "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}" ], "type": 1 }
需要提前创建好对应的Bean
由于传递过来的数据是String类型,因此需要转换一步
import cn.hutool.json.JSONObject; @PostMapping("/data/callback") public Object testResponse( @RequestBody JSONObject jsonObject ) { JSONArray jsonList = jsonObject.getJSONArray("list"); ArrayList<DataEntity> list = new ArrayList<>(); for (Object jsObject : jsonList){ DataEntity dataEntity = JSONObject.parseObject(jsObject.toString(), DataEntity.class); list.add(dataEntity); } Integer type = (Integer) jsonObject.get("type"); log.info(String.format("本次共接收%d条数据,type=%d",list.size(),type)); for (DataEntity dataEntity : list) { log.info(dataEntity.toString()); } }
在方法形参列表中添加@RequestBody注解
@RequestBody 作用是将请求体中的Json字符串自动接收并且封装为实体。如下:
@PostMapping("/queryCityEntityById") public Object queryCityEntityById(@RequestBody CityEntity cityEntity) { return ResultUtil.returnSuccess(cityService.queryCityById(cityEntity.getId())); }
如下:
@RestController public class HelloController { @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET) public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){ return "id:"+id+" name:"+name; } }
获取url参数值,默认方式,需要方法参数名称和url参数保持一致
localhost:8080/hello?id=1000,如下:
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam Integer id){ return "id:"+id; } }