Friday, 9 August 2013

JSON Parser

JSON Parser

Represents a parser for JSON-encoded content.
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 in JSONParser:All are instance  methods
·         clearCurrentToken
·         getBlobValue
·         getBooleanValue
·         getCurrentName
·         getCurrentToken
·         getDatetimeValue
·         getDateValue
·         getDecimalValue
·         getDoubleValue
·         getIdValue
·         getIntegerValue
·         getLastClearedToken
·         getLongValue
·         getText
·         getTimeValue
·         hasCurrentToken
·         nextToken
·         nextValue
·         readValueAs
·         readValueAsStrict
·         skipChildren
Simple Examples and Description:
Ø  clearCurrentToken
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
Returns the current token as a BLOB value.The current token must be of type JSONToken.VALUE_STRING and must be Base64-encoded.
Ø  getBooleanValue
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.
                Eg:
                String JSONContent ='{"isActive":true}';
JSONParser parser = JSON.createParser(JSONContent);
// Advance to the start object marker.
System.debug('parser.nextToken():'+parser.nextToken());
//output:START_OBJECT  which represents starting of object (‘{‘)
// Advance to the next value.
System.debug('parser.nextToken():'+parser.nextValue());
//output:VALUE_TRUE which represents
A value that corresponds to the “true” string literal
// Get the Boolean value.
Boolean isActive = parser.getBooleanValue();
System.debug('isActive:'+isActive);output:true



Ø  getCurrentName
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.
                Eg:
                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
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.
Eg:-
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
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.
                Eg:-
                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
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.
                Eg:See the above example just we need to replace getDateTimeValue() with getDateValue();
Ø  getDecimalValue
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.
                Eg:-Same as above
Ø  getDoubleValue
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.
                Eg:-Same as above
Ø  getIdValue
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.
Ø  getIntegerValue
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.
Ø  getLastClearedToken
Returns the last token that was cleared by the clearCurrentToken method.
Ø  getLongValue
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.
Ø  getText
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.
Ø  getTimeValue
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.
Ø  hasCurrentToken
Returns true if the parser currently points to a token; otherwise, returns false.


Ø  nextToken
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.
Ø  nextValue
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.
Ø  readValueAs
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.
If the JSON content to parse contains attributes not present in the Apex type specified in the argument, such as a missing field or object, this method ignores these attributes and parses the rest of the JSON content. However, for Apex saved using Salesforce.com API version 24.0 or earlier, this method throws a run-time exception for missing attributes.
Ø  readValueAsStrict
Deserializes JSON content into an object of the specified Apex type and returns the deserialized object. All attributes in the JSON content must be present in the specified type.The apexType argument specifies the type of the object that this method returns after deserializing the current value.
If the JSON content to parse contains attributes not present in the Apex type specified in the argument, such as a missing field or object, this method throws a run-time exception.
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.
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.
Eg:-
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);
    }  
}
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.
Eg1:
==
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;

}

1 comment:

Best Practices for Building Prompt Templates

 Hi, The following best practices should be considered when building prompt templates: Make sure that your prompt templates are concise and ...