Skip to main content
Added the apex tag !!
Link
Source Link

JSONGenerator writeObject() generates private properties

I have an Apex Class with some public properties and some private properties. When I use JSONGenerator.writeObject(foo), private properties are written into the JSON string. My code is below.

public class foo { 
   public String id;
   public String name;
   private String endpoint;
}

I have the following code that generates the JSON:

foo item = new foo();
item.Name = 'Truck';
system.JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeFieldName('requests');
gen.writeStartArray();
gen.writeStartObject();
gen.writeObjectField('method', method);
gen.writeFieldName('body');
gen.writeObject(item);
system.debug('gen.getAsString():' + gen.getAsString());

The JSON output looks like this:

    {"requests" : [ 
       {"body" : {
          "name" : "Truck",
          "id" : null,
          "endpoint" : null
          }
       } ]
     }

For some reason the private properties are being rendered. Is this normal behavior?