Search code examples
iosjsonsalesforceapex-code

obtaining the JSON body of a Http request in Salesforce


I am creating an iOS app with salesforce integration. The iOS app will send JSON data to salesforce in the body of an http request. How do I obtain the body as a JSON string in apex?

Thanks


Solution

  • Something like this (if you were making the callout from within Apex, otherwise use a webservice to capture the incoming call and parse in a similar way).

    Prepare your HTTP request object:

    // Prepare HTTP 
    HTTPResponse hTTPRes;
    HTTPRequest req = new HttpRequest();
    req.setTimeout(120000);
    

    Set your endpoint:

    req.setEndpoint(baseURL + callName + '?' + parameterString);
    

    Make callout:

    HTTP http = new HTTP();
    String body;
    hTTPRes = http.send(req);
    body = hTTPRes.getBody();
    

    Invoke JSON parser and parse your results:

    // Invoke JSON parser 
    JSONParser parser = System.JSON.createParser(body);
    
    // Parse JSON response to get individual field values.
    while(parser.nextToken() != null)
    {
       if((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'yourfield')) 
          // store values as you walk the JSON
    }