ResponseEntity不返回Post方法的json响应



在发送post方法时,我很难获得JSON格式的响应。我的控制器和响应类如下。此外,我在pom.xml中使用了Jackson依赖项,并且,我使用@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。

PostResponse类需要getter/setter

您的类中有A_VALUE和B_VALUE作为属性,而您正在设置A_VALUE和B_VALUE的值

自动连接PostService类,当您已经有了starter web依赖项时,还可以删除这些(Jackson(依赖项。我还建议您在类级别使用Lombok的@Data和@NoArgsConstructor注释。

尝试在类上放置注释@RestController

下面的类中有Getter和Setter吗?

public class PostResponse {
@JsonProperty("Avalue")
public String A_VALUE;
@JsonProperty("Bvalue")
public String B_VALUE;}

最新更新