Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation when decoding json using jackson

Tags:

java

json

jackson

I receive a json encoded string and then I decode it into a pojo, like this:

String json = ...

final ObjectMapper mapper = new ObjectMapper();
MyPojo obj  = mapper.readValue(json, MyPojo.class);

I want to be able to validate this input, but I'm not sure what's the "right way" of doing it.
Let's say MyPojo is defined like this:

@JsonIgnoreProperties(ignoreUnknown=true)
class MyPojo {
    public static enum Type {
        One,
        Two,
        Three;

        @JsonValue
        public String value() {
            return this.name().toLowerCase();
        }
    }

    private String id;
    private Type type;
    private String name;

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Type getType() {
        return this.type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

There are three things I want to validate:

  1. That all members have values
  2. That the enum value is part of the enumeration
  3. Test some or all values against some criteria (i.e.: min or max length, min or man number value, regular expression, etc)

If the validation fails I want to return a meaningful and readable message.

For the first and third issues I can simply check all the members of the object and see if any are null, and if not test them against the criteria, but this approach can get long and complicated when there are many fields.

As for the 2nd issue, if the value in the input does not match one of the enumeration values then a JsonMappingException is thrown, and so I managed to do this:

try {
    MyPojo obj  = mapper.readValue(json, MyPojo.class);
}
catch (JsonMappingException e) {
    return "invalid value for property: " + e.getPath().get(0).getFieldName();
}

But how do I get the value in the input so that I can return: invalid value: VALUE for property: PROPERTY?

Thanks.

like image 414
Nitzan Tomer Avatar asked Jul 06 '12 12:07

Nitzan Tomer


Video Answer


1 Answers

I would recommend using an implementation of JSR-303 Bean Validation. This specification defines a set of annotations and XML config files for specifying constraints that you wish to validation on your domain obects. The reference implementation is available here:

  • http://www.hibernate.org/subprojects/validator.html
like image 118
bdoughan Avatar answered Oct 26 '22 23:10

bdoughan