Jackson Validation when mapping JSON to POJO -


firstly must confess new web services , dropwizard framework.

i performing post request , trying parse json body pojo.

this works great when json in required format. however, when key in json, missing, pojo resorts default value.

my question is, there anyway of either checking json values or having jackson throw sort of exception if json key missing?

public class placedbetdecimal extends placedbet {      private double odds;      // empty constructor please jackson     public placedbetdecimal() {      }      public placedbetdecimal(@jsonproperty("bet_id") long bet_id,                             @jsonproperty("stake") int stake,                             @jsonproperty("odds") double odds) {          super.bet_id = bet_id;         super.stake = stake;         this.odds = odds;     }      public double getodds() {         return odds;     }      @override     public string tostring() {         return "placedbetfractional{" +                 "bet_id="+super.bet_id+                 "stake="+super.stake+                 "odds=" + odds +                 '}';     } } 

the json in body follows:

{     "bet_id": 1,     "odds": 11.0,     "stake": 10 } 

if reason, supplied body with:

{     "odds": 11.0,     "stake": 10 } 

then able catch instead of jackson auto filling bet_id 0.

any , appreciated.

instead of using primitives, use corresponding type wrappers, e.g. double instead of double, , mark them bean validation constraints @notnull.

my question is, there anyway of either checking json values or having jackson through sort of exception if json key missing?

in opinion, add bean validation constraints pojos , perform validations on incoming representations. if there @ least 1 constraint violation, dropwizard return 422 unprocessable entity response.

suppose have person like:

public class person {      @notempty // ensure name isn't null or blank     private string name;      @notnull @min(18) // @ least 18 years old!     private integer age;      // getters , setters } 

then, in our resource class, can add @valid or @validated annotation person:

@put public person replace(@valid person person) {     // stuff } 

if name or age fields missing, dropwizard return 422 unprocessable entity response detailing validation errors.


Comments