function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
laxmi narayan 11laxmi narayan 11 

Map json data to salesforce object

Hi there,

I have integration stuff. In this i callout to external api and get data in response. This is my code.

public class covidIntegrationCallout {
    public static HttpResponse makeCovidIntegrationCallout() {
        Http ht = new Http();
        HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.covid19india.org/state_district_wise.json');
        request.setMethod('GET'); 
        HttpResponse res = ht.send(request);
        System.debug('========='+res);
        System.debug('========='+res.getBody());
        List<Covid19__c> upsertState = new List<Covid19__c>();  
        Map<String,Object> results = (Map<String,Object>) JSON.deserializeUntyped(res.getBody());
         System.debug('----------'+results);   
        Map<String,Object> tempst = (Map<String,Object>)(results.get('State Unassigned'));
        for(Object lst:tempst.keySet()){ 
            system.debug('************'+lst); 
        }
return res;
    }
}

help me to map json data to salesforce custom object Covid19__c.

any help appriciated!

Thanks in Advance
ANUTEJANUTEJ (Salesforce Developers) 
Hi  Laxmi Narayan,

>> https://salesforce.stackexchange.com/questions/158493/field-mapping-from-json-response-to-custom-object

As mentioned in the above link, you will have to write a class to deserialize the json response.

For quick reference I am adding the selected best answer in the above link below:

You might consider writing a class to deserialize into. You can add an instance method to it that does additional parsing.
public class LeadResponse
{
    public final String fullName, personalPhone; // etc.
    public Lead getRecord()
    {
        String firstName, lastName;
        if (fulllName != null)
        {
            firstName = fullName.substringBefore('$');
            lastName = fullName.substringAfter('$');
        }
        return new Lead(
            FirstName = firstName,
            LastName = lastName,
            Phone = personalPhone
            // etc.
        );
    }
}
Then you would be able to do something like:
JSON payload; // get from webservice
LeadResponse response = (LeadResponse)JSON.deserialize(payload, LeadResponse.class);
Lead record = response.getRecord();
If you get a response with many Lead records, your deserialization process would change, but the class would stay the same:
JSON payload; // get from webservice
List<LeadResponse> responses = (List<LeadResponse>)
    JSON.deserialize(payload, List<LeadResponse>.class);

List<Lead> records = new List<Lead>();
for (LeadResponse response : responses)
    records.add(response.getRecord());

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.