在发送 post 方法时,我很难以 JSON 格式获得响应。我的控制器和响应类如下。我还使用了 Jackson 依赖项pom.xml
,我将@RestController
其用作 Controller 注释。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
<version>2.8.0</version>
</dependency>
我期望响应为 {Avalue:a, Bvalue:b} 但它返回 null 作为响应。你能帮我找到我失踪的地方吗?
@RestController
public class Controller{
private PostService postService;
@RequestMapping(value = "/create", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<PostResponse> create(@RequestBody VInfo v) {
VInfo created = postService.createVInfo(v);
PostResponse pr = new PostResponse();
if (created == null) {
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
} else {
pr.a_value= v.a_value;
pr.b_value= v.b_value;
return new ResponseEntity<PostResponse>(pr,HttpStatus.OK);
}
}
}
public class PostResponse {
@JsonProperty("Avalue")
public String A_VALUE;
@JsonProperty("Bvalue")
public String B_VALUE;
}
@Service
public class PostService {
@Autowired
private CreateVRepository postRepository;
public VInfo createVInfo(VInfo vInfo){
VInfo v1= new VInfo ();
v1.setA_VALUE(vInfo.getA_VALUE());
v1.setB_VALUE(vInfo.getB_VALUE());
postRepository.save(v1);
return v1;
}
}
我在控制器上使用了记录器,我可以看到记录器毫无问题地传递到其他括号。当我记录我的 pr.a 和 pr.b 对象时,它们会返回预期值。但是响应仍然返回 null。