0

I am passing request in JSON format to third party system but they want only to pass field which is not null else skip that field. I am trying to build logic to skip Null/Blank. Can someone please help.

Example :

{
    "group": "AA",
    "effectiveDt": "2019-12-31T12:00:00",
    "accountName": "ABCDDDDD",
    "Number": ,
    "trackingId": "122111xxx222"
  }

As "Number" is null so request should only have below field

{
    "group": "AA",
    "effectiveDt": "2019-12-31T12:00:00",
    "accountName": "ABCDDDDD",
    "trackingId": "122111xxx222"
}
  • 1
    Please include the code you're using and show where you're stuck in your implementation. – David Reed Jun 12 at 1:42
2

The cleanest way to generate JSON in Apex code is to use the JSON Class and that now includes this method:

public static String serialize(Object objectToSerialize, Boolean suppressApexObjectNulls)

that will not serialize null values when suppressApexObjectNulls is set to true.

PS

If the source of the data is an SObject (or some other sort of map where you know the keys) you can iterate over the fields and replace empty strings with nulls before serializing:

YourType__c sob = ...;
for (SObjectFied f : YourType__c.getDescribe().fields.getMap().values()) {
    if (f.getDescribe().isUpdateable()) {
        if (sob.get(f) == '') sob.put(f, null);
    }
}
  • It's not working actually. For example this code Map<String, Object> m = new Map<String, Object>{ 'x' => 'x', 'y' => '', 'z' => null }; system.debug(JSON.serialize(m, true)); gives me this output: {"z":null,"y":"","x":"x"}. Moreover, it will not suppress empty strings anyway, and the question is stated about this option too. – Mariia Illarionova Jun 12 at 8:39
  • @MariiaIllarionova See the PS. – Keith C Jun 12 at 10:13
  • Yes, sure, I understand, how to remove empty strings, however, suppressApexObjectNulls does not remove nulls, as it described in documentation. In my example it is shown with 'z' key, that appears in debug. – Mariia Illarionova Jun 12 at 12:14
  • Thanks Keith !! This solution worked perfectly !! – Sfdc_1184 Jun 12 at 12:18
  • @MariiaIllarionova My bad. I get the same result as you. Seems like suppressApexObjectNulls of true is broken. – Keith C Jun 12 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.