2

I've a POJO and I want to create an instance of this class from JSON. I'm using jackson for converting JSON to Object. I want to ensure that JSON will conain all properties of my POJO. The JSON may contain other extra fields but it must contain all the attributes of the POJO.

Example:

class MyClass {
    private String name;
    private int age;

    public String getName(){return this.name;}
    public void setName(String name){this.name = name;}
    public int getAge(){return this.age;}
    public void setAge(int age){this.age = age;}
}

JSON #1

{
    "name":"Nayan",
    "age": 27,
    "country":"Bangladesh"
}

JSON #2

{
    "name":"Nayan",
    "country":"Bangladesh"
}

Here, I want JSON#1 to be successfully converted to MyClass but JSON#2 should fail. How can I do this? Is there an annotation for this?

Nayan
  • 1,521
  • 2
  • 13
  • 27
  • Possible duplicate of [jackson-required-property](http://stackoverflow.com/questions/13756540/jackson-required-property) – Shane Voisard Apr 15 '15 at 12:30

1 Answers1

0

Well, there is an annotation that you could apply to your properties that say they are required.

@JsonProperty(required = true)
public String getName(){ return this.name; }

The bad part is, as of right now (2.5.0), validation on deserialization isn't supported.

...
Note that as of 2.0, this property is NOT used by BeanDeserializer: support is expected to be added for a later minor version.

There is an open issue from 2013 to add validation: Add support for basic "is-required" checks on deserialization using @JsonProperty(required=true)

mkobit
  • 43,979
  • 12
  • 156
  • 150