Search code examples
javajsonfasterxml

Can I restrict the possible values when deserializing from JSON?


I'm using the fasterxml library, and I have the following:

public class Test {
    public String value;
}

...

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static final ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws IOException {
        String json = "{\"value\":\"foo\"}";
        Test t = mapper.readValue(json, Test.class);
    }
}

Is it possible to restrict the possible values value can be?

For example, if the JSON was "{"value":"bar"}", I want Test t = mapper.readValue(json, Test.class); to throw an exception (or indicate an error somehow).


Solution

  • Through FasterXML (Jackson 2) directly, no. The only validation it will do is on the possible conversion from JSON types to a corresponding Java type.

    You can either do the validation yourself in the setter used for the corresponding field, throwing a runtime exception. For example

    @JsonProperty("value")
    public String setValue(String value) {
        if ("bar".equals(value)) {
            throw new RuntimeException("value " + value + " is inappropriate.");
        }
        this.value = value;
    }
    

    You can also write a custom JsonDeserializer that does the validation and fails on inappropriate values. There is an example for writing deserializers here and in other tutorials.