4

I am using a class from another module in my request.

public class KeyInput {
  @NotNull
  private Long id;
  @NotNull
  private String startValue;
  @NotNull
  private String endValue;
}

I cannot put @JsonIgnoreProperties(ignoreUnknown = true) annotation on this class, since the module does not contain jackson library.

Putting it on field level where I used it on my request class didn't work out.

@JsonIgnoreProperties(ignoreUnknown = true)
private List<KeyInput> keys;

Here is the incoming request. Notice the source of the problem, the two fields (name and type), which are not declared in KeyInput class.

{
    "id": 166,
    "name": "inceptionDate",
    "type": "DATE",
    "startValue": "22",
    "endValue": "24"
}

How am I supposed to tell the jackson to ignore the unknown fields if the class is not in my package?

P.S: I know I can get the keys as json string and serialize it using ObjectMapper (by setting the configuration DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to false), but I am looking for a cleaner solution here.

Also putting those fields in my class and never use it, is another dirty solution.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
starkm
  • 859
  • 1
  • 10
  • 21
  • Use `MixIn` feature. Take a look on some examples: [Dynamic addition of fasterxml Annotation?](https://stackoverflow.com/q/25290915/51591), [How to map Json to Proto using Jackson Mixin?](https://stackoverflow.com/q/59157263/51591), [Jackson conditional @JsonUnwrapped](https://stackoverflow.com/q/25425419/51591) – Michał Ziober Sep 02 '21 at 15:25

2 Answers2

2

Two ways come to my mind.

Method 1

Create an empty child class that inherit from KeyInput class. This is the easiest method.

@JsonIgnoreProperties(ignoreUnknown = true)
public class InheritedKeyInput extends KeyInput{}

Method 2

Create a custom de-serializer for KeyInput class.

public class KeyInputDeserializer extends JsonDeserializer<KeyInput> {

    @Override
    public KeyInput deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        KeyInput keyInput = new KeyInput();
        keyInput.setId(node.get("id").asLong());
        keyInput.setEndValue(node.get("startValue").textValue());
        keyInput.setStartValue(node.get("startValue").textValue());
        return keyInput;
    }
}

Bind this de-serializer to KeyInput using a configuration class

@Configuration
public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer {

    @Override
    public void customize(Jackson2ObjectMapperBuilder builder) {
        builder.failOnEmptyBeans(false)
                .deserializerByType(KeyInput.class, new KeyInputDeserializer());
    }
}
ray
  • 1,512
  • 4
  • 11
0

just simple add on above filed which you wanna ignore @JsonIgnore