Newer Version Available
JSON Parsing
Use the JSONParser class methods to parse
JSON-encoded content. These methods enable you to parse a JSON-formatted response that's
returned from a call to an external service, such as a web service callout.
The following are samples that show how to parse JSON strings.
Example: Parsing a JSON Response from a Web Service Callout
This example parses a JSON-formatted response using JSONParser methods. It makes a callout to a web service that returns a response in JSON format. Next, the response is parsed to build up a map from api version numbers to the release labels.
1public class JSONParserUtil {
2 public static void parseJSONResponse() {
3
4 // Create HTTP request to send.
5 HttpRequest request = new HttpRequest();
6 // Set the endpoint URL.
7 String endpoint = URL.getOrgDomainUrl().toExternalForm() + '/services/data';
8 request.setEndPoint(endpoint);
9 // Set the HTTP verb to GET.
10 request.setMethod('GET');
11 // Set the request header for JSON content type
12 request.setHeader('Accept', 'application/json');
13
14 // Send the HTTP request and get the response.
15 // The response is in JSON format.
16 Http httpProtocol = new Http();
17 HttpResponse response = httpProtocol.send(request);
18 System.debug(response.getBody());
19 /* The JSON response returned is the following:
20 {"label":"Summer '14","url":"/services/data/v31.0","version":"31.0"},
21 {"label":"Winter '15","url":"/services/data/v32.0","version":"32.0"},
22 {"label":"Spring '15","url":"/services/data/v33.0","version":"33.0"},
23 */
24 // Parse JSON response to build a map from API version numbers to labels
25 JSONParser parser = JSON.createParser(response.getBody());
26 Map<double, string> apiVersionToReleaseNameMap = new Map<double, string>();
27
28 string label = null;
29 double version = null;
30
31 while (parser.nextToken() != null) {
32
33 if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
34 switch on parser.getText() {
35 when 'label' {
36 // Advance to the label value.
37 parser.nextToken();
38 label = parser.getText();
39 }
40 when 'version' {
41 // Advance to the version value.
42 parser.nextToken();
43 version = Double.valueOf(parser.getText());
44 }
45 }
46 }
47
48 if(version != null && String.isNotEmpty(label)) {
49 apiVersionToReleaseNameMap.put(version, label);
50 version = null;
51 label = null;
52 }
53 }
54 system.debug('Release with Rainbow logo = ' +
55 apiVersionToReleaseNameMap.get(39.0D));
56 }
57}Example: 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.
1public static void parseJSONString() {
2 String jsonStr =
3 '{"invoiceList":[' +
4 '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
5 '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
6 '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
7 '"invoiceNumber":1},' +
8 '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
9 '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
10 '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
11 '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
12 ']}';
13
14 // Parse entire JSON response.
15 JSONParser parser = JSON.createParser(jsonStr);
16 while (parser.nextToken() != null) {
17 // Start at the array of invoices.
18 if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
19 while (parser.nextToken() != null) {
20 // Advance to the start object marker to
21 // find next invoice statement object.
22 if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
23 // Read entire invoice object, including its array of line items.
24 Invoice inv = (Invoice)parser.readValueAs(Invoice.class);
25 system.debug('Invoice number: ' + inv.invoiceNumber);
26 system.debug('Size of list items: ' + inv.lineItems.size());
27 // For debugging purposes, serialize again to verify what was parsed.
28 String s = JSON.serialize(inv);
29 system.debug('Serialized invoice: ' + s);
30
31 // Skip the child start array and start object markers.
32 parser.skipChildren();
33 }
34 }
35 }
36 }
37}
38
39// Inner classes used for serialization by readValuesAs().
40
41public class Invoice {
42 public Double totalPrice;
43 public DateTime statementDate;
44 public Long invoiceNumber;
45 List<LineItem> lineItems;
46
47 public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) {
48 totalPrice = price;
49 statementDate = dt;
50 invoiceNumber = invNumber;
51 lineItems = liList.clone();
52 }
53}
54
55public class LineItem {
56 public Double unitPrice;
57 public Double quantity;
58 public String productName;
59}