springboot接收Post请求Body的参数
赛尔号- 人气:0如何接收Post请求Body里的参数
ApiPost测试数据
{ "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 }
Java接收数据
需要提前创建好对应的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()); } }
SpringBoot获取参数常用方式
参数在body体中
在方法形参列表中添加@RequestBody注解
@RequestBody 作用是将请求体中的Json字符串自动接收并且封装为实体。如下:
@PostMapping("/queryCityEntityById") public Object queryCityEntityById(@RequestBody CityEntity cityEntity) { return ResultUtil.returnSuccess(cityService.queryCityById(cityEntity.getId())); }
PathVaribale获取url路径的数据
如下:
@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; } }
RequestParam获取请求参数的值
获取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; } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容