Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude null values in object while converting to JSON using Jackson 1.5?

Tags:

java

json

jackson

I am trying to create a Json object using Jackson library 1.5 but getting objects who have Null values also.

How can I get rid of the Null values?

Below is the code I am using.

    package com.test;
        public class Sample {

            public String name;

            public String surname;



            public Sample(String name, String surname) {
                this.name = name;
                this.surname = surname;
            }

            public String getName() {
                return name;
            }

            public String getSurname() {
                return surname;
            }


        }


        public static void main(String[] args){
        Sample sample = new Sample("Sam", null);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
        System.out.println(mapper.writeValueAsString(restRetrieveQuoteResponse));

        }
}

The issue here is, in mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false); WRITE_NULL_PROPERTIES is deprecated.

I have tried to find the alternative for this but could not find. Most of the solutions which are available are with Jackson 2.2. Can someone help me solving this for 1.5?

I have looked at here and here.

like image 878
Sam Avatar asked Dec 30 '25 23:12

Sam


2 Answers

You looked everywhere but at the javadoc it states to use inclusion as a rule of thumb most deprecated methods state what to use instead of them

like image 158
maczikasz Avatar answered Jan 01 '26 12:01

maczikasz


try using

mapper.setSerializationInclusion(Include.NON_NULL);
like image 44
Thirumalai Parthasarathi Avatar answered Jan 01 '26 12:01

Thirumalai Parthasarathi