You need to sign in to do that
Don't have an account?
mk2013
How to parse a list of JSON objects inside a controller
Hi,
I have a controller which makes HTTP callouts to a J2EE webapp, the callout returns a list of JSON objects.
I need to retrive values from this object and insert it into salesforce object, there is no VF page for this. I get the following list in response to my call.
[{"quoteId":"364926","baseModelName":"e-Studio Color Copier - Tandem LCF","accessoryNames":["Finier Rail"],"baseModelCost":20000.0,"skuNumber":"ESTU0CT"},{"quoteId":"364926","baseModelName":"e-Studio Copier - 4 Drawer","accessoryNames":["50 Sheet Stapling Finisher"],"baseModelCost":10000.0,"skuNumber":"ESTU0C"}]
To parse above list I first created an apex class as below
public class PrimaryQuoteObj {
public String quoteId;
public String baseModelName;
public List<String> accessorySKUs;
public Double baseModelCost;
public String skuNumber;
}
and then tried to parse the list in the controller using the above class like below.
global class ExtCalloutController {
WebService static void getPrimaryQuoteDetails(String id) {
HttpRequest req = new HttpRequest();
//Set HTTPRequest Method
req.setMethod('GET');
//Set HTTPRequest header properties
req.setHeader('Connection','keep-alive');
req.setEndpoint('http://cxyz.row.com/myApp/getPrimaryDetails.htm?qId='+id);
Http http = new Http();
try {
//Execute web service call here
HTTPResponse res = http.send(req);
System.debug('Response Body = ' + res.getbody());
PrimaryQuoteObj priQuotedetails =(PrimaryQuoteObj)System.JSON.deserialize(res.getbody(), PrimaryQuoteObj.class);
//Helpful debug messages
System.debug(res.toString());
System.debug('STATUS:'+res.getStatus());
System.debug('STATUS_CODE:'+res.getStatusCode());
} catch(System.CalloutException e) {
//Exception handling goes here....
}
// return null;
}
}
When parsing the JSON list I get the exception:
System.JSONException: Malformed JSON: Expected '{' at the beginning of object
I understand that this is because it's a list of JSON objects, trying to figure out how to loop through this list. I am a total newbie to salesForce and apex and any help is appreciated.
This reply may be not appropriate but,
I am sharing my idea.
The data came from JSON looks like a string. If so you can split using string methods and get the required value.
I already implemented using Sting methods, but am looking for a more elegant way to parse JSON list.
Thanks,
mk2013
Your payload sample is a list, have you tried
PrimaryQuoteObj priQuotedetails =(List<PrimaryQuoteObj>)System.JSON.deserialize(res.getbody(), List<PrimaryQuoteObj>.class);
also, it might be a typo but shouldn't accessorySKUs be accessoryNames on PrimaryQuoteObj class?