How to Fetch records from Web Services and put it into salesforce object.

H

Hi All,

We can fetch  records or values from  Web Services and can save the value into our Salesforce Object.The responce we are getting it is in JSON formate.Please follow the steps below:

Step 1.If you have already created the object, then make sure that all Fields are avaliable in that.

Step 2.Make a Visualforce Page which will contain a button. By pressing the button, response will fetch from web service and will get save into Salesforce object.Visualforce Code is::

<apex:page controller="MyController">
    <apex:pagemessages />
    <br />
    <apex:form >
        <apex:commandButton value="Sync Data" action="{!syncData}"/>
    </apex:form>
</apex:page>
Step 3.Then we have to make a Method which will responcible to get the Responce from the URL.  The code is:

public String fetchJSON(String endpoint)

{

try        {

Http httpProtocol = new Http();

HttpRequest request = new HttpRequest();

request.setEndPoint(endpoint);

request.setMethod(‘GET’);

HttpResponse response = httpProtocol.send(request);

return response.getBody();

}

catch(Exception ex)

{

return ”;

}

}

}

Step 4. Make a list and the type of the list will be that salesforce object.The list will hold the data, comming from Web Services.Then iterate the list and put the value into the  appropriate fields. Here is the code:

public class MyController

{

public PageReference syncData()

{

//Variable Declarations

List<Salesforce_obj__c> lstobj = new List<Salesforce_obj__c>();

Salesforce_obj__c obj;

//Read Web Service

if (!System.Test.isRunningTest())

response = fetchJSON(‘Web Service Url’);

//Parse JSON

JSONParser parser = JSON.createParser(response);

while (parser.nextToken() != null)

{

if (parser.getCurrentToken() == JSONToken.FIELD_NAME)

{

fieldName = parser.getText();

parser.nextToken();

if(fieldName == ‘Id’)

{

obj = new Salesforce_obj__c();

obj.Id__c= parser.getText();

}

if(fieldName == ‘name’)

{

obj = new Salesforce_obj__c();

obj.name__c= parser.getText();

}

else if(fieldName == ‘DateAdded’)

{

obj.Date_Added__c= Date.valueOf(parser.getText());

lstobj.add(obj);

count ++;

}

}

}

//Update object

upsert lstobj Id__c;   //Id__c is external id

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, count + ‘ Data Synced’));

return null;

}

 

 

About the author

rajesh.chatterjee
By rajesh.chatterjee

Category