22

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(); 

1 Answer 1

36

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}

2
  • That should do the trick
    – GrayB
    Nov 27, 2013 at 17:34
  • one thing to note, serialization includes private variables, so take care to use transient with those if you don't want them output in a public rest service accidentally Mar 30, 2015 at 23:45

You must log in to answer this question.

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