How does JSON serialize apex work?

601    Asked by bruce_8968 in Salesforce , Asked on Feb 10, 2023

 I have an object that's pretty extensive (lots of properties and child relationships). I'd like to serialize it. So I am doing the following:

Proposal__c proposal = (Proposal__c) getRecord();
String s = JSON.serialize(proposal);
The output:
{"attributes":      
    {
       "type":"WWK_Proposal__c",
       "url":"/services/data/v29.0/sobjects/WWK_Proposal__c/a0cM0000001BfBLIA0"
    },
    "Id":"a0cM0000001BfBLIA0"
}

And that is all. How can I get the entire object serialized, perhaps even including its child relationships?

Answered by Audrey Berry

You probably need to query more fields to expose them in JSON serialize apex. It would help if you posted your getRecord() code, but the following ought to work:


SObject getRecord()
{
    List fieldsToQuery = Proposal__c.SObjectType.getDescribe().fields.getMap().values();
    String fields = String.join(fieldsToQuery, ', ');
    String soqlQuery = String.format('SELECT {0} FROM Proposal__c LIMIT 1', new List { fields });
    return Database.query(soqlQuery)
}
Proposal__c proposal = (Proposal__c) getRecord();
String s = JSON.serialize(proposal);


Your Answer

Interviews

Parent Categories