Sayed Uz Zaman
Sayed Uz Zaman

Reputation: 656

How to apply json ignore annotation on a rest controller method endpoint in spring boot?

I have a class called Customer

Customer{
   private int ID;
   private IDCard idCard;
}

and IDCard.Java

IDCard{
   private int id;
   private int score;
}

I have two endpoints, endpoint01 and endpoint02. So when I add a customer using endpoint01, providing score is mandatory. But when I add customer using endpoint02, score is not mandatory.

As I am using Same customer model in both endpoint's controller method, Jackson throws error because on endpoint02 I didn't provide score. In this case its clear that I can not apply json ignore in my IDCard model. So how can I tell my endpoint02 to ignore score field if it is not present and deserialize only if the field is present in the json object.

This is my endpoint02

@RequestMapping(method=RequestMethod.POST, value="/add",headers="Accept=application/json")
public @ResponseBody Map<String,List<String>> add(@RequestBody Customer customer)  {
    return customerSvc.add(customer);
}

Upvotes: 2

Views: 750

Answers (2)

elias zaman
elias zaman

Reputation: 21

You can apply ignore annotation on the specific property.

Upvotes: 2

what you want is annotation on your POJO and not on your ENDPOINT

IDCard{

   @JsonProperty(vaue="id" , required=false)
   private int id;
   @JsonProperty(vaue="score" , required=false)
   private int score;

}

this will enable your fields to be avoided while deserializing the object.

Note : take care of encapsulation.

Upvotes: 2

Related Questions