[SalesForce] JSON Serialize vs JSON Generator

I have a build a REST API @HTTP POST using apex class and I was able to serialize the account info for the specified columns.

@RestResource(urlMapping='/test/Netsuite_api/*')
global class RestTestController {
      @HttpPost
  global static void getTestAccount() {
  RestRequest req = RestContext.request;
  RestResponse res = RestContext.response;
  res.addHeader('Content-Type', 'application/json');
  String jsonResponse = '';
  String AccountName= req.params.get('Account_Name');
       // No account_name parameter was found; return status 400
 if(AccountName== null) {
        res.statusCode = 400;
        jsonResponse = '{"response": {"status": "Failure", "message":  "MissingRequiredQueryParameter Account_Name"}}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }
// Get the list of accounts that match the account_name sent in the request.
    List<Account> accounts = [SELECT Id, Name, Phone, Fax, Website
                              FROM Account
                              WHERE Name =: AccountName];
// No accounts with matching account_name
    if( accounts.isEmpty()) {
        res.statusCode = 400;
        jsonResponse = '{"response": {"status": "Failure", "message": "No account matching Account_Namewas found"}}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }

// At least 1 account was found, JSON serialize it and send it back.
    try {
        res.statusCode = 200;
        jsonResponse = Json.serialize(accounts[0]);
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    } catch ( Exception ex ) {
        res.statusCode = 500;
        jsonResponse = '{"response": {"status": "Failure", "message": "' + ex + '"}}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }
}
}

How can I serialize the other objects that have a master detail and lookup relationship with Account? Do I need to use the JSON Generator class separately for this ?How do Json Serialize and Generator methods really varies?

Best Answer

If you have any specific requirement regarding JSON structure, you need to go for JSON Generator. But if you are okay with the JSON syntax JSON.serialize() is giving, that is more than enough.

Regarding serializing all child relations of account, you can use JSON.serialize() itself. You need to query child relationships also while querying account. Check below example,

List<Account> accounts = [SELECT Id, Name, Phone, Fax, Website,
                              (SELECT Id,Name FROM Contacts)
                              FROM Account
                              WHERE Name =: AccountName];
if(!accounts.isEmpty()){
    String jsonData = JSON.serialize(accounts[0]);
}

Try debugging the jsonData string. If that JSON format is not good for you, go ahead and create it in your own format using JSON Generator.

Related Topic