[SalesForce] Returning a value from JSON Object

Hi I am trying to return a second value pair (string) from a JSON object using APEX's own built-in parser. The API query takes a string variable of a web domain.

However, I am getting a strange error I've never seen before:

Line: 7, Column: 0
expecting a semi-colon, found '<EOF>'

Here's my code:

 public class companyIDFetcher {

    public string companyIDFetcher (string domain){ 
        HTTPRequest companyIDRequest = new HTTPRequest();
        companyIDRequest.setEndpoint('https://api.api.com/api/v0/something/something/id?domain_name=' + domain);
        companyIDRequest.setMethod('GET');

        HTTP n = new HTTP();
        HTTPResponse companyIDResponse = n.send(companyIDRequest);
        string MosaicAPIBasicRequest = companyIDResponse.getBody();

        JSONParser parser = JSON.createParser(MosaicAPIBasicRequest);
        parser.nextToken();
        parser.nextToken();
        parser.nextValue();
        String companyID = parser.getText();
        system.debug(companyID);
        return companyID;
    }

Any advice would be appreciated.

Here's a JSON Response that I am receiving when making a http request:

{
  "meta": {
    "number_of_records": 3
  },
  "data": "13458245"
}

Best Answer

try this, Probably you need to change it with the correct field name

String response = '{"meta": {"number_of_records": 3},"data": "13458245"}';

JSONParser parser = JSON.createParser(response);
while (parser.nextToken() != null) {
    if(parser.getCurrentName() == 'number_of_records') {
        parser.nextValue();
        System.debug(parser.getDecimalValue());
    }
}
Related Topic