1

I am trying to get the field value from the object. If I loop through the object it looks like

Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestbody.toString());
for(Object obj: (List<Object>)params.get('records')){
   System.debug('obj=====>'+obj);
}

how to get the obj.Banking?

LOOP RESULT

  • obj=>{attributes={referenceId=ref1, type=Account}, industry=Banking, name=SampleAccount1, numberOfEmployees=100, phone=1111111111, website=www.salesforce1.com}
  • obj=>{attributes={referenceId=ref1, type=Account}, industry=Banking, name=SampleAccount1, numberOfEmployees=100, phone=1111111111, website=www.salesforce1.com}

I want to get the industry, name values. Although I was able to get it working using the wrapper when I used JSON.deserialize like below

WrapperData wrapRecords =  (WrapperData) System.JSON.deserialize(RestContext.request.requestbody.toString(), WrapperData.class);
for(Integer i=0; i<wrapRecords.records.size() ; i++){
    Account acc = new Account ();
    acc.Name = wrapRecords.records[i].name;
    acc.industry = wrapRecords.records[i].industry;
}

I was able to get the records using JSON.deserialize but would like to know if this possible with JSON.deserializeUntyped. I saw somewhere choosing deserializeUntyped over deserialize is better when it comes to performance. I don't know how to approach. Any advise would be appreciated. Thank you so much.

1 Answer 1

2

I saw somewhere choosing deserializeUntyped over deserialize is better when it comes to performance.

AFAIK, the performance between deserialize and deserializeUntyped is minimal. With a class + deserialize, its much easier to parse the JSON response.

Having said that, this can still be done with deserializeUntyped as:

// hardcoding the string as per one in question
String requestBodyString = '{"records": [{"attributes":{"referenceId":"ref1", "type":"Account"}, "industry":"Banking", "name":"SampleAccount1", "numberOfEmployees":100, "phone":1111111111, "website":"www.salesforce1.com"}]}';

Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(requestBodyString);
for(Object obj: (List<Object>)params.get('records')){
    // the result of obj is JSON, so convert it to map
    Map<String, Object> objMap = (Map<String, Object>) obj;
    String industry = (String) objMap.get('industry');
    System.debug(industry);
}

The key here is to convert a complex object or JSON property to a Map<String, Object>, then you can extract the appropriate value from JSON.

1
  • I was able to get it working. Thanks. This helped me to avoid writing extra classes.
    – NBR
    Commented Dec 30, 2021 at 6:41

You must log in to answer this question.

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