4

I'm trying to do my first REST integration between PHP and Salesforce, and am having some trouble understanding how to handle the JSON objects. Basically I'm sending over a list/array of objects in JSON format and then want to put them back in object format.

Right now, my JSON string looks like

[{"TransDate":"2017-01-01","Sales":"161776","InvoiceNo":"C017665","CustNm":"Coomber, Skip","ProductGroup":"APCCSERV"},...]

Which I believe should be an array of objects

Then I'm trying to parse it in Salesforce with the following

    if (response.getStatusCode() == 200) {
        // Deserialize the JSON string into collections of primitive data types.
         List<SalesData> resultList = (list<SalesData>)JSON.deserializeStrict(response.getBody(), SalesData.class);

       //  system.debug(results);
    }        
}

Class SalesData {
    Date TransDate;
    String Sales;
    String InvoiceNo;
    String CustNm;
    String ProductGroup;

}

But I get the following error

"Line: 19, Column: 1 System.JSONException: Malformed JSON: Expected '{' at the beginning of object"

Which maybe makes sense because I am passing in an array of objects not an object, but then how do I get around that?

side note the PHP I'm using is

    while (odbc_fetch_row($result) ) { 
    $row = new stdClass();

    $TransDate = odbc_result($result, 'TransDate'); $row->TransDate = $TransDate;
    $Sales = odbc_result($result, 'Sales'); $row->Sales = $Sales;
    $InvoiceNo = odbc_result($result, 'InvoiceNo'); $row->InvoiceNo = $InvoiceNo;
    $CustNm = odbc_result($result, 'CustNm'); $row->CustNm = $CustNm;
    $ProductGroup = odbc_result($result, 'ProductGroup'); $row->ProductGroup = $ProductGroup;




    array_push($post_data, $row);

    }


if (isset($_POST)) {

    $json_params = file_get_contents("php://input");
    echo json_encode($post_data);

}

1 Answer 1

9

You have an array of objects, so you should use:

List<SalesData> resultList =
    (list<SalesData>)
    JSON.deserializeStrict(
         response.getBody(),
         List<SalesData>.class);

The problem is that you told the JSON parser that it was expecting a single SalesData object. Instead, we have to tell the JSON parser to expect a list of SalesData objects, so we use List<SalesData>.class to indicate this.

2
  • Krone, You might want to consider using JSON.deserialize vs. JSON.deserializeStrict. Using deserializeStrict makes Salesforce and your PHP Service "tightly" coupled, and that's not always desirable. YMMV @sfdcfox good stuff! Jan 9, 2017 at 19:48
  • What do you mean by tightly coupled?
    – Krone
    Jan 24, 2017 at 0:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .