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.

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.