Require JSON field with JAXB

I have the following.

@XmlRootElement public class SomeObject { private String requiredField; @XmlElement(name="address", required=true) public String getRequiredField() { return requiredField; } public void setRequiredField(String requiredField) { this.requiredField = requiredField; } } 

However, when the corresponding Jersey resource consumes the JSON necessary to create this object, it successfully creates the object with or without a field, which is annotated as necessary.

Using Jersey and JAXB, or directly related technologies, is there a way to ensure that the value of the consumed property is present in the consumed JSON? What is missing in the above example?

Example:

I would like it to reject the call, for example the following: since the JSON body does not contain a value for the required field.

 curl -i -X POST -H 'content-type:application/json' -d '{}' http://some/uri 

Rather, I would like something like this to work.

 curl -i -X POST -H 'content-type:application/json' -d '{"requiredField":"Hello, world!"}' http://some/uri 
+4
source share
1 answer

You can set a default value for your field.

 @XmlRootElement public class SomeObject { private String requiredField = "Hello world!"; //... } 

now, if you do not set a new value for this field at run time, then in JSON you will see "Hello world!" string

+1
source

All Articles