JSONParser Methods

Represents a parser for JSON-encoded content.

Usage

Use the System.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.

Methods

The following are instance methods of the System.JSONParser class.

Method Arguments Return Type Description
clearCurrentToken Void Removes the current token.

After this method is called, a call to hasCurrentToken returns false and a call to getCurrentToken returns null. You can retrieve the cleared token by calling getLastClearedToken.

getBlobValue Blob Returns the current token as a BLOB value.

The current token must be of type JSONToken.VALUE_STRING and must be Base64-encoded.

getBooleanValue Boolean Returns the current token as a Boolean value.

The current token must be of type JSONToken.VALUE_TRUE or JSONToken.VALUE_FALSE.

The following example parses a sample JSON string and retrieves a Boolean value.
String JSONContent =
    '{"isActive":true}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the Boolean value. 
    
Boolean isActive = parser.getBooleanValue();
getCurrentName String Returns the name associated with the current token.

If the current token is of type JSONToken.FIELD_NAME, this method returns the same value as getText. If the current token is a value, this method returns the field name that precedes this token. For other values such as array values or root-level values, this method returns null.

The following example parses a sample JSON string. It advances to the field value and retrieves its corresponding field name.
String JSONContent = '{"firstName":"John"}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the field name for the current value. 
    
String fieldName = parser.getCurrentName();
// Get the textual representation  
    
// of the value. 
    
String fieldValue = parser.getText();
getCurrentToken System.JSONToken Returns the token that the parser currently points to or null if there's no current token.
The following example iterates through all the tokens in a sample JSON string.
String JSONContent = '{"firstName":"John"}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the next token. 
    
while (parser.nextToken() != null) {
    System.debug('Current token: ' +
        parser.getCurrentToken());
}
getDatetimeValue Datetime Returns the current token as a date and time value.

The current token must be of type JSONToken.VALUE_STRING and must represent a Datetime value in the ISO-8601 format.

The following example parses a sample JSON string and retrieves a Datetime value.
String JSONContent =
'{"transactionDate":"2011-03-22T13:01:23"}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the transaction date. 
    
Datetime transactionDate = 
   parser.getDatetimeValue();
getDateValue Date Returns the current token as a date value.

The current token must be of type JSONToken.VALUE_STRING and must represent a Date value in the ISO-8601 format.

The following example parses a sample JSON string and retrieves a Date value.
String JSONContent =
   '{"dateOfBirth":"2011-03-22"}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the date of birth. 
    
Date dob = parser.getDateValue();
getDecimalValue Decimal Returns the current token as a decimal value.

The current token must be of type JSONToken.VALUE_NUMBER_FLOAT or JSONToken.VALUE_NUMBER_INT and is a numerical value that can be converted to a value of type Decimal.

The following example parses a sample JSON string and retrieves a Decimal value.
String JSONContent =
   '{"GPA":3.8}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the GPA score. 
    
Decimal gpa = parser.getDecimalValue();
getDoubleValue Double Returns the current token as a double value.

The current token must be of type JSONToken.VALUE_NUMBER_FLOAT and is a numerical value that can be converted to a value of type Double.

The following example parses a sample JSON string and retrieves a Double value.
String JSONContent =
   '{"GPA":3.8}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the GPA score. 
    
Double gpa = parser.getDoubleValue();
getIdValue ID Returns the current token as an ID value.

The current token must be of type JSONToken.VALUE_STRING and must be a valid ID.

The following example parses a sample JSON string and retrieves an ID value.
String JSONContent =
   '{"recordId":"001R0000002nO6H"}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the record ID. 
    
ID recordID = parser.getIdValue();
getIntegerValue Integer Returns the current token as an integer value.

The current token must be of type JSONToken.VALUE_NUMBER_INT and must represent an Integer.

The following example parses a sample JSON string and retrieves an Integer value.
String JSONContent =
   '{"recordCount":10}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the record count. 
    
Integer count = parser.getIntegerValue();
getLastClearedToken System.JSONToken Returns the last token that was cleared by the clearCurrentToken method.
getLongValue Long Returns the current token as a long value.

The current token must be of type JSONToken.VALUE_NUMBER_INT and is a numerical value that can be converted to a value of type Long .

The following example parses a sample JSON string and retrieves a Long value.
String JSONContent =
   '{"recordCount":2097531021}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the record count. 
    
Long count = parser.getLongValue();
getText String Returns the textual representation of the current token or null if there's no current token.

No current token exists, and therefore this method returns null, if nextToken has not been called yet for the first time or if the parser has reached the end of the input stream.

For an example, see getCurrentName.

getTimeValue Time Returns the current token as a time value.

The current token must be of type JSONToken.VALUE_STRING and must represent a Time value in the ISO-8601 format.

The following example parses a sample JSON string and retrieves a Datetime value.
String JSONContent =
   '{"arrivalTime":"18:05"}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Advance to the start object marker. 
    
parser.nextToken();
// Advance to the next value. 
    
parser.nextValue();
// Get the arrival time. 
    
Time arrivalTime = parser.getTimeValue();
hasCurrentToken Boolean Returns true if the parser currently points to a token; otherwise, returns false.
nextToken System.JSONToken Returns the next token or null if the parser has reached the end of the input stream.

Advances the stream enough to determine the type of the next token, if any.

For an example, see getCurrentName.

nextValue System.JSONToken Returns the next token that is a value type or null if the parser has reached the end of the input stream.

Advances the stream enough to determine the type of the next token that is of a value type, if any, including a JSON array and object start and end markers.

For an example, see getCurrentName.

readValueAs System.TypeapexType Any type Deserializes JSON content into an object of the specified Apex type and returns the deserialized object.

The apexType argument specifies the type of the object that this method returns after deserializing the current value.

The following example parses a sample JSON string and retrieves a Datetime value. Before being able to run this sample, you must create a new Apex class as follows:
public class Person {
    public String name;
    public String phone;
}
Next, insert the following sample in a class method or trigger:
// JSON string that contains a Person object. 
    
String JSONContent =
    '{"person":{' + 
        '"name":"John Smith",' +
        '"phone":"555-1212"}}';
JSONParser parser = 
   JSON.createParser(JSONContent);
// Make calls to nextToken()  
    
// to point to the second 
    
// start object marker. 
    
parser.nextToken();
parser.nextToken();
parser.nextToken();
// Retrieve the Person object 
    
// from the JSON string. 
    
Person obj = 
   (Person)parser.readValueAs(
      Person.class);
System.assertEquals(
   obj.name, 'John Smith');
System.assertEquals(
   obj.phone, '555-1212');
skipChildren Void Skips all child tokens of type JSONToken.START_ARRAY and JSONToken.START_OBJECT that the parser currently points to.

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 select Your Name | Setup | Security Controls | Remote Site Settings.
public class JSONParserUtil {
    @future(callout=true)
    public static void parseJSONResponse() {        
        Http httpProtocol = new Http();
        // Create HTTP request to send. 
    
        HttpRequest request = new HttpRequest();
        // Set the endpoint URL. 
    
        String endpoint = 'http://www.cheenath.com/tutorial/sfdc/sample1/response.php';
        request.setEndPoint(endpoint);
        // Set the HTTP verb to GET. 
    
        request.setMethod('GET');
        // Send the HTTP request and get the response. 
    
        // The response is in JSON format. 
    
        HttpResponse response = httpProtocol.send(request);
        System.debug(response.getBody());
        /* The JSON response returned is the following:
        String s = '{"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 JSON response to get all the totalPrice field values. 
    
        JSONParser parser = JSON.createParser(response.getBody());
        Double grandTotal = 0.0;
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                (parser.getText() == 'totalPrice')) {
                // Get the value. 
    
                parser.nextToken();
                // Compute the grand total price for all invoices. 
    
                grandTotal += parser.getDoubleValue();
            }
        }
        system.debug('Grand total=' + grandTotal);
    }   
}

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.
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;
}

The System.JSONToken Enum

Enum Value Description
END_ARRAY The ending of an array value. This token is returned when ']' is encountered.
END_OBJECT The ending of an object value. This token is returned when '}' is encountered.
FIELD_NAME A string token that is a field name.
NOT_AVAILABLE The requested token isn't available.
START_ARRAY The start of an array value. This token is returned when '[' is encountered.
START_OBJECT The start of an object value. This token is returned when '{' is encountered.
VALUE_EMBEDDED_OBJECT An embedded object that isn't accessible as a typical object structure that includes the start and end object tokens START_OBJECT and END_OBJECT but is represented as a raw object.
VALUE_FALSE The literal “false” value.
VALUE_NULL The literal “null” value.
VALUE_NUMBER_FLOAT A float value.
VALUE_NUMBER_INT An integer value.
VALUE_STRING A string value.
VALUE_TRUE A value that corresponds to the “true” string literal.
© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.