In this blog we will learn about JSON parsing in salesforce. In salesforce, we use methods of JSONParser class to parse the JSON-encoded string/content that is returned from a call to an external service such that web service(HTTP) callout.

Let’s understand the JSONParser methods by doing an example as explained below.

Dummy Json String:

-> Here we have a dummy  JSON string. We will parse this JSON string and create a record for product and pricebookEntry in salesforce.

{  
   "title":"Shirt",
   "body_html":"This is product's description field",
   "variants":[  
      {  
         "price":"21.00",
      },
      {  
         "price":"24.00",
      }
   ]
}

-> For each variant we create a pricebookEntry in salesforce.

Key Points:

Here we have some JSONParser methods, which we are going to use to parse the above string.

1). JSON.createParser(jsonString) : Create new Parser

2). nextToken() : Locate  cursor to next token.

3). getCurrentToken() : To get the current token value.

4). getCurrentName() : To get the current field name.

5). nextValue() :Locate  cursor to next value.

6). getText() : To get the text value of the token.

Note: For more information on JSONParser methods Click Here

Apex Code

1). Create a new pricebook (Name= ‘Demo’) from Pricebook>>New Pricebook>>Name= ‘Demo’>> Save.

2). Create an apex class jsonParserExample to parse the above string.

public class jsonParserExample {
	
    /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */
   
    public jsonParserExample() {
        
        Pricebook2 pb = [SELECT Id FROM Pricebook2 WHERE isStandard = true limit 1]; // Get the standard Pricebook Id
        Pricebook2 cpb = [SELECT Id FROM Pricebook2 WHERE Name = 'Demo' limit 1];	 // Get the Custom Pricebook Id
        Product2 prod = new Product2();												 // New Product Object  	
        PricebookEntry pbe = new PricebookEntry();									 // New PricebookEntry Object
        List<PricebookEntry> list_pbe = new List<PricebookEntry>();                  // List of pricebook Entry
        
        // Dummy String to Parse
        
        String jsonString = '{\"title\":\"Shirt\",\"body_html\":\"This is products description field\",\"variants\":[{\"price\":\"21.00\"},{\"price\":\"24.00\"} ]}';
        
        // Create parser of dummy string
        
        JSONParser parser = JSON.createParser(jsonString);
        
        // Parsing of string
        
        while(parser.nextToken()!= null) {
            if(parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                parser.nextValue();
                if(parser.getCurrentName() == 'title') {
                    prod.Name = parser.getText();
                } else if (parser.getCurrentName() == 'body_html') {
                    prod.Description = parser.getText();
                } else if (parser.getCurrentName() == 'variants') {
                    while(parser.nextToken()!= JSONToken.END_ARRAY) {
                        if(parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                			parser.nextValue();
                            if(parser.getCurrentName() == 'price') {
                                pbe.UnitPrice = Decimal.valueOf(parser.getText());
                            }  
                        } else if(parser.getCurrentToken() == JSONToken.END_OBJECT) {
                            if(pbe.UnitPrice != null)
                            {
                             	list_pbe.add(pbe);   
                            }
                            pbe = new PricebookEntry();
                            continue;
                        } else if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                            continue;
                        }
                    }
                }
            }
        }
        
        // Create the Product in salesforce.
        if(prod.name != null) {
            try{
                insert prod;
            } catch(Exception ex) {
                system.debug(ex);
            }
        }
        
        // Create the pricebookEntry
        if(prod.Id != null && list_pbe.size()>0) {
            for(PricebookEntry p : list_pbe) {
                p.Product2Id = prod.Id;
            }
            list_pbe[0].Pricebook2Id = pb.Id;
            list_pbe[1].Pricebook2Id = cpb.Id;
            
            try{
                insert list_pbe;
            } catch(Exception ex) {
                system.debug(ex);
            }
        }
    }
}

2). Now open Execute Anonymous window (Ctrl+E) and execute the following code.

jsonParserExample a = new jsonParserExample();

Now, go to Product and check the created record.

Output

 

Support

That’s all for JSON Parsing In Salesforce, still if you have any further query feel free to contact us, we will be happy to help you https://wedgecommerce.com/contact-us/.

Leave A Reply

Please verify that you are not a robot.

Tell us about Your Company

How can we help you with your business?




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home