If I am querying RestResponse using below query:

List<Account> accList = [SELECT Name, AccountNumber FROM Account WHERE LastName = :req.params.get('name')];

For any account with an empty AccountNumber, the response will look like this :

    "Name":"SMT TEST",
                               // No AccountNumber Here
    "Name":"SMTH TEST",

Is there any way to format with an empty string instead : "AccountNumber":"" ?

  • can you please add more details, why you want such format? this looks like an x-y problem. – rahul gawale Feb 28 at 11:39
  • It's just a requirement – wih Feb 28 at 12:57

You're not going to get an empty string unless you write some code to make it so. Salesforce does not store empty strings in the database, only null; when you query a record with a Text field that does not contain data, null is what you get back.

When you serialize an object to JSON, which appears to be what you're doing, a queried sObject's fields that are null are omitted from the resultant JSON.

System.debug(JSON.serialize([SELECT AccountNumber FROM Account LIMIT 1]));

results in seeing no AccountNumber entry at all

08:17:15:006 USER_DEBUG [2]|DEBUG|{"attributes":{"type":"Account","url":"/services/data/v45.0/sobjects/Account/0011R00001ypMKsQAM"},"Id":"0011R00001ypMKsQAM","RecordTypeId":"01236000000STbiAAG"}

If you explicitly set the AccountNumber to null or '', you will get a null or '' entry in generated JSON:

List<Account> acts = [SELECT AccountNumber FROM Account LIMIT 1];

for (Account a : acts) {
    a.AccountNumber = '';


08:25:03:007 USER_DEBUG [7]|DEBUG|[{"attributes":{"type":"Account","url":"/services/data/v45.0/sobjects/Account/0011R00001ypMKsQAM"},"Id":"0011R00001ypMKsQAM","RecordTypeId":"01236000000STbiAAG","AccountNumber":""}]

I think this requirement is a mistake, but if you absolutely must, that's going to be the way to go.

  • I though so, thanks for the answer – wih Mar 1 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.