0

I am using Jackson 2 library and I am trying to deserilize a JSON response, which looks like:

{
    "employee": [
    {},
    {
        "Details": [
            {
                "Name": "value",
                "Lastname": "value"
            }
        ]
    }
]}

For some reasons, there is an empty element at my employee array. Is it possible to discard that element and avoid to deserialize it, during deserialization process? Currently, my code deserialize the empty employee as an Employee POJO class with null fields.

My code looks like:

ObjectMapper mapper = new ObjectMapper();
Empoyee[] array = mapper.readValue(json, Empoyee[].class);

PS. I cannot touch the JSON response. It is what it is...

3 Answers3

1

You need to write custom deserialiser or filter out empty objects after deserialisation process. Second approach sounds much easier because except custom deserialiser for bean you need to extend already implemented deserialiser for arrays (com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer) and filter out null or empty beans.

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • Your answer solves my case with two different ways. I will accept your answer as a solution to my problem. Appart from the fact that the second approach is easier, can you elaborate a little more why is it preferable? – Konstantinos Raptis Mar 06 '19 at 02:29
0

First, please make sure that you have setters, getters and constructors, after that, you can use the following:

Employee employee = mapper.readValue(yourJson, Employee.class);
Ido Segal
  • 430
  • 2
  • 7
  • 20
  • I have constructors at my POJO classes. The code above creates the employee object. It has nothing to do with the question, which is how we discard the empty object during deserialization process. – Konstantinos Raptis Mar 08 '19 at 11:36
0

Hope it will help you .

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setSerializationInclusion(Include.NON_EMPTY); 

Or

ObjectMapper mapper = new ObjectMapper ().configure(
        DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).setSerializationInclusion(
                JsonInclude.Include.NON_NULL);
vaquar khan
  • 10,864
  • 5
  • 72
  • 96