Let’s see how to get a JSON string based on the attributes of an Apex class in Salesforce
public class MyClass {
public String field1;
public String field2;
public String getJson(){
JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartObject();
if(this.field1 != null) gen.writeStringField('field1', this.field1);
if(this.field2 != null) gen.writeStringField('field2', this.field2);
gen.writeEndObject();
return gen.getAsString();
}
}