我想使用 Spring Boot 构建一个 Rest Controller 。但是 Spring 无法自动将 Json 转换为 Java 对象。是的:
- 我有空的构造函数
- 我尝试了@RequestParam、@RequestBody、@RequestPart
- 我的 JSON 参数是有效的(我尝试用 Gson 解析,它成功了)
这是我的 REST Controller :
@RestController
public class HelloController {
@RequestMapping(value= "/abc", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody MyResponse handlePurchase(@RequestParam A request){
return new MyResponse("Simply the best");
}
}
这是 A.java:
public class A implements Serializable {
private B something;
public B getSomething() {
return Something;
}
public void setSomething(B something) {
this.Something = something;
}
@Override
public String toString() {
return "A [Something=" + something + "]";
}
public A(B something) {
super();
this.Something = something;
}
public A() {
super();
}
}
这是 A.java 使用的 B.java:
public class B implements Serializable {
private String something;
private int catsNumber;
private int dogsNumber;
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something = something;
}
public int getCatsNumber() {
return catsNumber;
}
public void setCatsNumber(int catsNumber) {
this.catsNumber = catsNumber;
}
public int getDogsNumber() {
return dogsNumber;
}
public void setDogsNumber(int dogsNumber) {
this.dogsNumber = dogsNumber;
}
@Override
public String toString() {
return "B [something=" + something + ", catsNumber=" + catsNumber + ", dogsNumber=" + dogsNumber + "]";
}
public B() {
super();
}
}
希望有人能帮我解决这个问题,但都没有成功:
- Spring.io
- 其他 Stackoverflow 问答
最佳答案
@RequestParam
表示一个url参数http://foo.com?parameter=x
。使用post时,需要定义一个@RequestBody
@RequestMapping(value= "/abc", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody MyResponse handlePurchase(@RequestBody A a){
return new MyResponse("Simply the best");
}
关于java - Spring Boot REST Controller 没有将给定的 Json 参数解析为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38913753/