ResponseEntity do not return json response for Post Method

1.4k Views Asked by At

I'm having a hard time at getting response as JSON format while sending post method. My controller and response class is below. Also I used Jackson dependencies at my pom.xml and, I'm using @RestController as Controller annotation.

<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>

I'm expecting response to be as {Avalue:a, Bvalue:b} but instead it returns null for response. Can you help me to find where I'm missing?

@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;
    }

}

I used logger at my controller and I can see logger passing to else brackets without any problem. When I log my pr.a and pr.b objects, they returns expected values. However response still returns null.

4

There are 4 best solutions below

0
On BEST ANSWER

You have A_VALUE and B_VALUE as attributes in your class whereas you're setting values of a_value and b_value.

Do Autowire your PostService class and also remove these(Jackson) dependencies when you have starter-web dependency already. I would also recommend you to use Lombok's @Data and @NoArgsConstructor annotations at class level.

1
On

Do you have Getters and Setters in below class ?

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

Try to put annotation @RestController on the class.

2
On

you will need getter/setter for PostResponse class