简体   繁体   中英

How to avoid deserialize empty JSON Array elements from JSON String while using Jackson

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...

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:

首先,请确保您具有setter,getter和构造函数,然后,可以使用以下代码:

Employee employee = mapper.readValue(yourJson, Employee.class);

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);

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