0

I have a json response which I got from external system using its endpoint. Now I need to create account records in Salesforce using that response.

Below is my Rest Callout code:

 String jsonbody = '{ ' +
              '"accountName": "Test"' +
              '}' ;
  HttpRequest req = new HttpRequest();
  req.setMethod('GET');
  req.setTimeout(120000);
  req.setHeader('content-type', 'application/json');
  req.setHeader('Content-Length', String.valueOf(jsonBody.length()));
  req.setEndpoint('<endpoint>');
  System.debug('Input Request:' + jsonBody);
  req.setBody(jsonBody);   
  Http http = new Http();
  HTTPResponse res = http.send(req);
  System.debug(res.toString());
  System.debug('STATUS:' + res.getStatus());
  System.debug('STATUS_CODE:' + res.getStatusCode());
  String response = res.getBody();
system.debug('Output==>'+ response);

Below is my JSON response:

{
    "code": 200,
    "value": {
        "data": [
            {
                "accountName": "Test Account",
                "address": "Test Address"
                "licenseCode": "01"
            }
        ],
        "message": "Account Details retrieved successfully."
    }
}

Now, using JSON2APEX, I have created this below JsonParser class

    public class JsonParser{
            public value value{get;set;}
            public Integer code{get;set;}
        public class value{
            public String message{get;set;}
            public Integer code{get;set;}
            public list<data> data{get;set;}
        }
        public class data{
            public String accountName{get;set;}
            public String address{get;set;}
            public String licenseCode{get;set;}
        }
public static JsonParser parse(String json){
        return (JsonParser) System.JSON.deserialize(json, JsonParser.class);
    }
    }

Here, licenseCode is the unique field and now, I'm stuck at the point where I need to create Account records in my org using the Json response above. Can anyone please suggest on how to do so. Thanks!

5
  • Now try to deserialize the JSON like - JSON.deserialize( res.getBody(), JSONParser.class) and now you will receive List<JSONParser>, which you can use to insert the accounts – Ysr Shk Nov 2 '20 at 11:55
  • @YsrShk, if possible, could you please provide the skelliton of the suggested logic. Thanks! – SFDCUser Nov 2 '20 at 12:06
  • What have you tried? Where are you stuck? – Derek F Nov 2 '20 at 12:06
  • @YsrShk, I have updated my JsonParser class with deserialize method. (Please find updated code above) Could you please suggest on how to create account using this JSON. Thanks! – SFDCUser Nov 2 '20 at 14:02
  • Please take a look at DML Basics trailhead, then give it another shot. – identigral Nov 2 '20 at 17:19
0

I think this example can help you.

Parse a JSON String and Deserialize It into Objects

This example uses a hardcoded JSON string, which is the same JSON string returned by the callout in the previous example. In this example, the entire string is parsed into Invoice objects using the readValueAs method. This code also uses the skipChildren method to skip the child array and child objects and parse the next sibling invoice in the list. The parsed objects are instances of the Invoice class that is defined as an inner class. Because each invoice contains line items, the class that represents the corresponding line item type, the LineItem class, is also defined as an inner class. Add this sample code to a class to use it.
    public static void parseJSONString() {
    String jsonStr = 
        '{"invoiceList":[' +
        '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
            '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
            '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
                '"invoiceNumber":1},' +
        '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
            '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
            '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
            '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
        ']}';

    // Parse entire JSON response.
    JSONParser parser = JSON.createParser(jsonStr);
    while (parser.nextToken() != null) {
        // Start at the array of invoices.
        if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
            while (parser.nextToken() != null) {
                // Advance to the start object marker to
                //  find next invoice statement object.
                if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    // Read entire invoice object, including its array of line items.
                    Invoice inv = (Invoice)parser.readValueAs(Invoice.class);
                    system.debug('Invoice number: ' + inv.invoiceNumber);
                    system.debug('Size of list items: ' + inv.lineItems.size());
                    // For debugging purposes, serialize again to verify what was parsed.
                    String s = JSON.serialize(inv);
                    system.debug('Serialized invoice: ' + s);

                    // Skip the child start array and start object markers.
                    parser.skipChildren();
                }
            }
        }
    }
} 

// Inner classes used for serialization by readValuesAs(). 

public class Invoice {
    public Double totalPrice;
    public DateTime statementDate;
    public Long invoiceNumber;
    List<LineItem> lineItems;
    
    public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) {
        totalPrice = price;
        statementDate = dt;
        invoiceNumber = invNumber;
        lineItems = liList.clone();
    }
}  

public class LineItem {
    public Double unitPrice;
    public Double quantity;
    public String productName;
}

This is from the official documentation

Not the answer you're looking for? Browse other questions tagged or ask your own question.