Exclude properties from Apex class when serializing to JSON

Is it possible to delete class properties dynamically in Apex

Example:

public class BananaHolder() {
   public boolean isRipe;
   public boolean isDelicious;
   public integer somePropertyThatShouldntBeSentOverJson;
   public string JSON() { return JSON.serialize(this); }
}

BananaHolder banana = getRandomBanana();
// Delete somePropertyThatShouldntBeSentOverJson property
String jsonString = banana.JSON(); 

Answer

You could always make the offending property transient, then it won’t be included in the JSON (link to transient docs)

public class BananaHolder {
   public boolean isRipe;
   public boolean isDelicious;
   public transient integer somePropertyThatShouldntBeSentOverJson;
   public string JSON() {
        return JSON.serialize(this);
    }
}

BananaHolder banana = new BananaHolder();
String jsonString = banana.JSON(); 
System.debug(jsonString);

returns

DEBUG|{“isRipe”:null,”isDelicious”:null}

Attribution
Source : Link , Question Author : GrayB , Answer Author : Doug B

Leave a Comment