+ Start a Discussion

Upserting records from JSON

I have a requirement to upsert Policy records using JSON response obtained from external system.

below is my apex code:
HttpRequest req = new HttpRequest();
  req.setHeader('Authorization', 'Bearer ' + '<bearer token>');
  Http http = new Http();
  HTTPResponse res = http.send(req);
  String response = res.getBody();
JsonParser jsondes = (JsonParser) JSON.deserialize(response, JsonParser.class);

I have a JSON Parser class and it is as follows:
public class JSONParser{
    public Integer code;
    public cls_value value;
    public class cls_value {
        public cls_data[] data;
        public String message;
        public Integer code;    
    public class cls_data {
        public String agencyName;
        public String agentID;  
        public string id;   

Now, from the above code peice, ID is unique and if the id matches with existing Policy__c's Unique_ID__c field value, the record should be updated. Else, the record should be inserted.

Can anyone please let me know on how to do so.

Create list of records and then call upsert method. If record exists with matching unique id then it will update the record else it will insert the record.

You can use DML upsert sattement or Database upsert method.

DML Statement -> upsert listOfRecords Unique_ID__c


Database upsert method -> Database.upsert(listOfRecords ,Policy__c.Fields.Unique_ID__c,true)

AbhishekAbhishek (Salesforce Developers) 
I can see your query is answered here,


If it helps close this thread,So that we can keep the community clean.