0

I am trying to dynamically create JSON body to send as payload in REST method. Code:

List<Transaction__c> trans1 = new List<Transaction__c>([Select Id, 
    Transaction_Count__c, Total_Discount__c, Total_Cost__c, CreatedDate
    FROM Transaction__c
    WHERE Id = 'a015g000003WFxNAAW'
    LIMIT 1
]);

TransactionJson obj = new TransactionJson(trans1);

public class TransactionJson {
    public String jsonString {get;set;}
    public TransactionJson(List<Transaction__c> transList){
        
        List<Transaction__c> trans = transList;
        
        System.JSONGenerator js = json.createGenerator(true);
        js.writeStartObject();
        js.writeFieldName('keys');
        js.writeStartObject();
        js.writeStringField('TransactionID', trans.get(0).Id);
        js.writeEndObject();
        js.writeFieldName('values');
        for(Transaction__c t : trans){
            js.writeStartObject();
            js.writeNumberField('TotalCost', t.Total_Cost__c);
            js.writeEndObject();
        }
        js.writeEndObject();
        jsonString = js.getAsString();
        System.debug('body = ' + jsonString);
    }
}


String body2 = JSON.serialize(obj);

System.debug('body2 = ' + body2);

I am getting the following output. Why am I getting the escape characters? Also I need to return the body and all values as string itself. Thanks. 12:30:06:022 USER_DEBUG [38]|DEBUG|body2 = {" jsonString":"{\n "keys" : {\n "TransactionID" : "a015g000003WFxNAAW"\n },\n "values" : {\n "TotalCost" : 1005.00\n }\n}"}

1 Answer 1

0

You're likely getting escaped newlines because you're double-serializing things. jsonString is already serialized, and you're serializing your entire TransactionJSON instance.

That aside, using JSONGenerator is generally not the way to go. It's very verbose, and prone to mistakes. The recommended approach is to create apex classes that mirror the data structure you want your JSON to have, or just create a Map<String, Object>.

The Map<String, Object> approach might look like this

Map<String, Object> dataToSerialize = new Map<String, Object>{
    'keys' => new Map<String, Object>{
        'transactionId' => myRec.Id
    },
    'values' => new Map<String, Object>{
        'totalCost' => myRec.Total_Cost__c
    }
};

String theJSON = JSON.serialize(dataToSerialize);
1
  • Thanks. Appreciate you looking at it. Will try this way. Thanks again.
    – user91213
    Dec 23, 2020 at 16:26

You must log in to answer this question.