How to generate a JSON in Salesforce Apex

Patterned ceramic floor
Reading Time: < 1 minutes

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);
        if(this.field1 != null) gen.writeStringField('field1', this.field1);
        if(this.field2 != null) gen.writeStringField('field2', this.field2);
        return gen.getAsString();

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.

Related posts

Leave a Reply

%d bloggers like this: