[SalesForce] JSON Parsing of REST response

I am trying to integrate our Salesforce with Yodlee.
I have been successfully able to send and recieve REST response to their test server.
My issue is with the REST response body.

Their REST response is as follows

{"account":[{"CONTAINER":"creditCard","providerAccountId":10339026,"accountName":"CREDIT CARD","accountStatus":"ACTIVE","url":"BILL_VALID","accountNumber":"************8614","isAsset":false,"balance":{"amount":1636.44,"currency":"USD"},"id":10757807,"lastUpdated":"2017-08-05T14:42:38Z","includeInNetWorth":true,"providerId":"16441","providerName":"Dag Site","accountType":"OTHER","availableCash":{"amount":600,"currency":"USD"},"availableCredit":{"amount":1363,"currency":"USD"},"totalCashLimit":{"amount":600,"currency":"USD"},"totalCreditLine":{"amount":3000,"currency":"USD"},"isManual":false,"createdDate":"2017-07-26T06:08:36Z","refreshinfo":{"statusCode":0,"statusMessage":"OK","lastRefreshed":"2017-08-05T14:42:38Z","lastRefreshAttempt":"2017-08-05T14:42:38Z","nextRefreshScheduled":"2017-08-07T10:14:30Z"}},{"CONTAINER":"bank","providerAccountId":10339026,"accountName":"TESTDATA1","accountStatus":"ACTIVE","accountNumber":"503-5623xxx","isAsset":true,"balance":{"amount":9044.78,"currency":"USD"},"id":10757718,"lastUpdated":"2017-08-06T20:20:00Z","includeInNetWorth":true,"providerId":"16441","providerName":"Dag Site","availableBalance":{"amount":65454.78,"currency":"USD"},"currentBalance":{"amount":9044.78,"currency":"USD"},"accountType":"SAVINGS","isManual":false,"createdDate":"2017-07-26T06:08:36Z","refreshinfo":{"statusCode":0,"statusMessage":"OK","lastRefreshed":"2017-08-06T20:20:00Z","lastRefreshAttempt":"2017-08-06T20:20:00Z","nextRefreshScheduled":"2017-08-07T22:48:59Z"},"holderProfile":[{"name":{"displayed":"accountHolder"}}]},{"CONTAINER":"bank","providerAccountId":10339026,"accountName":"TESTDATA","accountStatus":"ACTIVE","accountNumber":"503-1123xxx","isAsset":true,"balance":{"amount":44.78,"currency":"USD"},"id":10757717,"lastUpdated":"2017-08-06T20:20:00Z","includeInNetWorth":true,"providerId":"16441","providerName":"Dag Site","availableBalance":{"amount":54.78,"currency":"USD"},"currentBalance":{"amount":44.78,"currency":"USD"},"accountType":"CHECKING","isManual":false,"createdDate":"2017-07-26T06:08:36Z","refreshinfo":{"statusCode":0,"statusMessage":"OK","lastRefreshed":"2017-08-06T20:20:00Z","lastRefreshAttempt":"2017-08-06T20:20:00Z","nextRefreshScheduled":"2017-08-07T22:48:59Z"},"holderProfile":[{"name":{"displayed":"accountHolder"}}]}]}

Simply put, their REST response contains array of objects.
Each account (credit card, bank etc) is represented as an object in the array.

I am interested in getting only the highlighted items.

enter image description here

I thought of using JSON parsing.
I am indeed able to consume the response and create a parser from it.

Shown below

public class JSONParserUtil {

    @future(callout=true)
    public static void parseJSONResponse() {        
        Http httpProtocol = new Http();
        // Create HTTP request to send.
        HttpRequest request = new HttpRequest();
        // Set the endpoint URL.
        String endpoint = 'https://developer.api.yodlee.com:443/ysl/restserver/v1/accounts';
        request.setEndPoint(endpoint);
        // Set the HTTP verb to GET.
        request.setMethod('GET');

        request.setHeader('Authorization','XXX');


        // Send the HTTP request and get the response.
        // The response is in JSON format.
        HttpResponse response = httpProtocol.send(request);
        System.debug(response.getBody());

       List<Yodlee_Accounts__c> acclst = new List<Yodlee_Accounts__c>();

       JSONParser parser = JSON.createParser(response.getBody());
       while (parser.nextToken() != null) {

              System.debug('parser.getCurrentName() => '+ parser.getCurrentName());
       System.debug('parser.getCurrentToken() => '+ parser.getCurrentToken());
       System.debug('parser.getText() => '+ parser.getText());

        }


       }
}

But I am not sure how to traverse the parser and get only the highlighted data.
I am aware that JSON string has something called START_OBJECT but I am not sure how to use that to get only my data elements.

Can someone help ?

Best Answer

Don't bother using JSONParser. It's inefficient, and really only meant for porting Java code, as far as I can tell. Since you're only concerned with a few elements, you can just do the following:

public class JSONParserUtil {
    public class AccountList {
        public AccountItem[] account;
    }
    public class AccountItem {
        public String CONTAINER, accountName, accountStatus;
        public Integer providerAccountId;
    }

    @future(callout=true)
    public static void parseJSONResponse() {        
        Http httpProtocol = new Http();
        // Create HTTP request to send.
        HttpRequest request = new HttpRequest();
        // Set the endpoint URL.
        String endpoint = 'https://developer.api.yodlee.com:443/ysl/restserver/v1/accounts';
        request.setEndPoint(endpoint);
        // Set the HTTP verb to GET.
        request.setMethod('GET');

        request.setHeader('Authorization','XXX');


        // Send the HTTP request and get the response.
        // The response is in JSON format.
        HttpResponse response = httpProtocol.send(request);
        System.debug(response.getBody());

        List<Yodlee_Accounts__c> acclst = new List<Yodlee_Accounts__c>();

        // Parse the data according to the AccountList class
        AccountList data = (AccountList)JSON.deserialize(response.getBody(), AccountList.class);
        // Iterate over the data
        for(AccountItem item: data.account) {
            // Do stuff with item...
        }
    }
}
Related Topic