赞
踩
我想弄清楚是否可以将JSON对象传递给其他API,或者将多个参数传递给该API?以及如何在Spring中读取这些参数?让我们假设网址如下所示:
例1:http:// localhost:8080 / api / v1 / mno / objectKey?id = 1& name = saif
传递JSON对象是否有效,如下面的url?
例2:http:// localhost:8080 / api / v1 / mno / objectKey / {“id”:1,“name”:“Saif”}
问题:
1)是否可以像往常一样将JSON对象传递给url?
2)我们如何传递和解析Ex.1中的参数?
我试着写一些方法来实现我的目标,但找不到合适的解决方案?
我试图将JSON对象作为@RequestParam传递
http:// localhost:8080 / api / v1 / mno / objectKey?id = 1出现意外错误(type = Unsupported Media Type,status = 415).内容类型“null”不受支持
http:// localhost:8080 / api / v1 / mno / objectKey / id = 1出现意外错误(type = Not Found,status = 404).没有可用的消息
http:// localhost:8080 / api / v1 / mno / objectKey / {“id”:1}出现意外错误(type = Not Found,status = 404).没有可用的消息
@RequestMapping(value="mno/{objectKey}",
method = RequestMethod.GET,
consumes="application/json")
public List getBook4(@RequestParam ObjectKey objectKey) {
...
}
我试图将JSON对象作为@PathVariable传递
@RequestMapping(value="ghi/{objectKey}",method = RequestMethod.GET)
public List getBook2(@PathVariable ObjectKey objectKey) {
...
}
我创建了这个对象来保存id参数和其他参数,如名称等….
class ObjectKey{
long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
解决方法:
(1) Is it possible to pass a JSON object to the url like in Ex.2?
不,因为http:// localhost:8080 / api / v1 / mno / objectKey / {“id”:1,“name”:“Saif”}不是有效的URL.
如果你想以RESTful方式做,请使用http:// localhost:8080 / api / v1 / mno / objectKey / 1 / Saif,并定义你的方法如下:
@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)
public Book getBook(@PathVariable int id, @PathVariable String name) {
// code here
}
(2) How can we pass and parse the parameters in Ex.1?
只需添加两个请求参数,并提供正确的路径.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)
public Book getBook(@RequestParam int id, @RequestParam String name) {
// code here
}
更新(来自评论)
What if we have a complicated parameter structure ?
06002
将其作为POST发送,其中包含请求正文中的JSON数据,而不是URL,并指定application / json的内容类型.
@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")
public Book getBook(@RequestBody ObjectKey objectKey) {
// code here
}
标签:java,spring,json,rest,spring-mvc
来源: https://codeday.me/bug/20191003/1851258.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。