Chetan
Chetan

Reputation: 1151

Cant map json to POJO

My controller looks like given below.

@CrossOrigin
@RequestMapping(value = "/addenquiry", method = RequestMethod.POST, produces = "application/json")
public Response<Enquiry> addEnquiry(@RequestBody Enquiry enquiry,HttpSession session) {
    Response<Enquiry> response = new Response<Enquiry>();


@Component
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Enquiry {

    private String enqId;

    //Getters and setters which are public

However when I pass the Json using

{
    "enqId;":"875421ekhrfkejhsjdf"
}

It is not getting mapped , and prints the null.

Upvotes: 0

Views: 106

Answers (1)

Patrick
Patrick

Reputation: 12744

You have to delete the @Component annotation in your Enquiry class. If you add a Spring annotation like @Component, @Controller, @Service you specify that the class will be a spring bean. In default the bean will be a singleton bean and just lives ones in the context.

In your case you want to post a new Enquiry Object by every request. Behind the scenes spring and jackson will do that for you. Without the @Component annotation it will be a normal POJO and does not exist in the spring context.

Site note: If you really want that Enquiry is in the spring context you can leave @Component annotation and add the scope prototype.

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Enquiry {}

This specify that spring creates a new instance everytime you ask for it.

Upvotes: 3

Related Questions