3

I have Json array containing null value in array.

{
  myArray: [ null ]
}

How to configure Jackson ObjectMapper to ignore such null array elements - as if it was empty array []?

Constrains:

  • No control of source class - it is a third party class
  • Array element type is unknown upfront
  • Array(s) name is unknown upfront
Michal Foksa
  • 11,225
  • 9
  • 50
  • 68
  • 1
    I don’t believe Jackson has this out of the box. You’ll need a custom deserializer. Or strip it yourself from the pojo. – Sotirios Delimanolis Mar 17 '21 at 15:06
  • @SotiriosDelimanolis Do you know a way how to plugin some post-processor to ObjectMapper? – Michal Foksa Mar 17 '21 at 15:07
  • 2
    No, I think it’ll be quite involved process. Find the standard list/set/collection and array deserializers, wrap them in the processor(s), then reregister them to deserialize those types. Might be easier to change your server ‍♂️ – Sotirios Delimanolis Mar 17 '21 at 15:17

2 Answers2

2

You can use contentNulls property from JsonSetter annotation. Your POJO class could look like below:

class ArrayWrapper {
    private List<String> myArray;

    @JsonSetter(contentNulls = Nulls.SKIP)
    public void setMyArray(List<String> myArray) {
        this.myArray = myArray;
    }

    public List<String> getMyArray() {
        return myArray;
    }
}

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • It seems to go in correct direction, but I cannot modify POJOs (or very hardly). I am looking for a solution with configuration ObjectMapper itself only. – Michal Foksa Mar 18 '21 at 06:31
  • @MichalFoksa, use `MixIn` feature. Examples: [Dynamic addition of fasterxml Annotation?](https://stackoverflow.com/a/25306786/51591), [Jackson conditional @JsonUnwrapped](https://stackoverflow.com/a/25435990/51591) – Michał Ziober Mar 18 '21 at 08:19
  • :( Mixin is not generic - it does not apply for every array / list. – Michal Foksa Mar 18 '21 at 08:41
  • @MichalFoksa, could you edit your question and add more details? Could you create an example where `MixIn` does not apply to array/list? – Michał Ziober Mar 18 '21 at 09:08
-1

Maybe @JsonIclude works?

   @JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)

http://fasterxml.github.io/jackson-annotations/javadoc/2.9/com/fasterxml/jackson/annotation/JsonInclude.html?is-external=true

PhilBa
  • 732
  • 4
  • 16