Marc M.
Marc M.

Reputation: 3791

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 make this object it successfully creates the object, with or without the field that is annotated as required.

Using Jersey and JAXB, or directly related technologies, is there a way to ensure that a value for requiredField is present in the consumed JSON? What's missing from the example above?

Example:

What I would like is it to reject a call such as the following, as the JSON body does not contain a value for requiredField.

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

Rather I would want something like this to work.

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

Upvotes: 4

Views: 346

Answers (1)

Ilya
Ilya

Reputation: 29693

You can set default value to your field.

@XmlRootElement
public class SomeObject {

    private String requiredField = "Hello world!"; 

    //...  
}

now if you don't set new value to this field at runtime, then in JSON you will see "Hello world!" string

Upvotes: 1

Related Questions