Newer Version Available

This content describes an older version of this product. View Latest

JSON Parsing

Using the JSONParser class methods, you can parse JSON-encoded content.

Use the JSONParser methods to parse a response that's returned from a call to an external service that is in JSON format, such as a JSON-encoded response of a Web service callout. The following are samples that show how to parse JSON strings.

Sample: Parsing a JSON Response from a Web Service Callout

This example shows how to parse a JSON-formatted response using JSONParser methods. This example makes a callout to a Web service that returns a response in JSON format. Next, the response is parsed to get all the totalPrice field values and compute the grand total price. Before you can run this sample, you must add the Web service endpoint URL as an authorized remote site in the Salesforce user interface. To do this, log in to Salesforce and from Setup, click Security Controls | Remote Site Settings.
1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class JSONParserUtil {
18    @future(callout=true)
19    public static void parseJSONResponse() {        
20        Http httpProtocol = new Http();
21        // Create HTTP request to send.
22        HttpRequest request = new HttpRequest();
23        // Set the endpoint URL.
24        String endpoint = 'https://docsample.herokuapp.com/jsonSample';
25        request.setEndPoint(endpoint);
26        // Set the HTTP verb to GET.
27        request.setMethod('GET');
28        // Send the HTTP request and get the response.
29        // The response is in JSON format.
30        HttpResponse response = httpProtocol.send(request);
31        System.debug(response.getBody());
32        /* The JSON response returned is the following:
33        String s = '{"invoiceList":[' +
34        '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
35            '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
36            '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
37                '"invoiceNumber":1},' +
38        '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
39            '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
40            '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
41            '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
42        ']}'; 
43        */
44
45        // Parse JSON response to get all the totalPrice field values.
46        JSONParser parser = JSON.createParser(response.getBody());
47        Double grandTotal = 0.0;
48        while (parser.nextToken() != null) {
49            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
50                (parser.getText() == 'totalPrice')) {
51                // Get the value.
52                parser.nextToken();
53                // Compute the grand total price for all invoices.
54                grandTotal += parser.getDoubleValue();
55            }
56        }
57        system.debug('Grand total=' + grandTotal);
58    }   
59}

Sample: Parsing a JSON String and Deserializing 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. It also uses the skipChildren method to skip the child array and child objects and to be able to parse the next sibling invoice in the list. The parsed objects are instances of the Invoice class that is defined as an inner class. Since 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.
1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static void parseJSONString() {
18    String jsonStr = 
19        '{"invoiceList":[' +
20        '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
21            '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
22            '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
23                '"invoiceNumber":1},' +
24        '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
25            '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
26            '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
27            '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
28        ']}';
29
30    // Parse entire JSON response.
31    JSONParser parser = JSON.createParser(jsonStr);
32    while (parser.nextToken() != null) {
33        // Start at the array of invoices.
34        if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
35            while (parser.nextToken() != null) {
36                // Advance to the start object marker to
37                //  find next invoice statement object.
38                if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
39                    // Read entire invoice object, including its array of line items.
40                    Invoice inv = (Invoice)parser.readValueAs(Invoice.class);
41                    system.debug('Invoice number: ' + inv.invoiceNumber);
42                    system.debug('Size of list items: ' + inv.lineItems.size());
43                    // For debugging purposes, serialize again to verify what was parsed.
44                    String s = JSON.serialize(inv);
45                    system.debug('Serialized invoice: ' + s);
46
47                    // Skip the child start array and start object markers.
48                    parser.skipChildren();
49                }
50            }
51        }
52    }
53} 
54
55// Inner classes used for serialization by readValuesAs(). 
56
57public class Invoice {
58    public Double totalPrice;
59    public DateTime statementDate;
60    public Long invoiceNumber;
61    List<LineItem> lineItems;
62    
63    public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) {
64        totalPrice = price;
65        statementDate = dt;
66        invoiceNumber = invNumber;
67        lineItems = liList.clone();
68    }
69}  
70
71public class LineItem {
72    public Double unitPrice;
73    public Double quantity;
74    public String productName;
75}