3

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.

1
  • How do you want to remove it, through apex or JS? Nov 26, 2018 at 10:15

2 Answers 2

9

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;
8
  • Wow, I didnt knew this param exists, I was using String replace to remove nulls. iwritecrappycode.wordpress.com/2014/07/16/… Nov 26, 2018 at 10:24
  • 1
    @PranayJaiswal This was a new feature sometime around Winter 15/Spring 15 (it's mentioned in the docs). Older API versions didn't suppress nulls, then there was one version that did, and then they let us specify.
    – sfdcfox
    Nov 26, 2018 at 10:32
  • We are using another class JSON generator to build the template and from this class sending the wrapperdata. Is there anyway I can do something like this ContactInfo.Country = null ? I have updated the class in question. Nov 26, 2018 at 11:18
  • @shuklayogesh As long as you're using null values, you can suppress them. If you're getting empty strings, then someone did that intentionally and should be fixed. Since you have a constructor... public ContactInfo(String town, String State, String Country) { this.town = town == ''? null: town; this.State = state == ''?: state; this.Country = Country == ''? null: country; }
    – sfdcfox
    Nov 26, 2018 at 11:24
  • Isn't the default behavior true and you would only need to set it if you want to exhibit different behavior?
    – Adrian Larson
    Nov 26, 2018 at 13:54
0

if you are trying to remove with apex while serializing then use below method from JSON class

public static String serialize(Object objectToSerialize, Boolean suppressApexObjectNulls)

suppressApexObjectNulls => Type: Boolean If true, remove null values before serializing the JSON object.

Reference

If you are trying to delete from js then try

delete obj.ContactInfo.Country;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .