简体   繁体   中英

Validation when decoding json using 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 (ie: 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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM