[SalesForce] How to remove key-value from JSON if it has empty value

I have this inner Class which has contactInfo to be sent as JSON now I want to remove the one key value if that has empty value:

public class ContactInfo {
        public String town;
        public String State;
        public String Country;
    public ContactInfo(String town, String State, String Country){
    town = town;
    State = state;
    Country = Country;
    }
    }

{"ContactInfo":[
        {
        "town":"Bangalore",
        "State":"KA",
        "Country":"" // If this is case then remove this attribute itself
        }
       ]

}

I am using remove string for empty value which doesn't look good.

Best Answer

If you use null values, they will not be serialized when providing the "supressNulls" flag:

ContactInfo demo = new ContactInfo();
demo.town = 'Anywhere';
demo.State = 'New York';
demo.Country = null;
System.debug(json.serialize(demo, true));

Output:

{"demo":"Anywhere","State":"New York"}

Empty string values are still values. In almost all cases, Apex doesn't use empty strings, instead returning null. For most remaining cases, you can always use null explicitly:

demo.town = townInput == ''? null: townInput;
Related Topic