The post How to do JSON Parsing of a wrapper class in Salesforce appeared first on Salesforce Next Gen.
]]>We use JSON parsing to interchange data from a web server.
Data is always shared as a string from a web server
To make the data understandable to our system, we do JSON Parsing, and the data becomes a JavaScript object.
Example of JSON Parsing.
‘{ “name”:”John”, “age”:30, “city”:”New York”}’
Use the JavaScript function JSON.parse() to convert text into a JavaScript object
var obj = JSON.parse(‘{ “name”:”John”, “age”:30, “city”:”New York”}’);
The above example is to do parsing in JavaScript, To do JSON Parsing in Salesforce we have quiet similar approach.
But first we should understand few terms before we begin the JSON parsing concept.
To convert an object into a stream of string characters is known as serialization, i. e Object -> String. Once we serialize an object we can transport it over the web server.
To convert a stream of string into an object is known as deserialization, or simply opposite of serialization is called deserialization, normally it is a response received from a web server. String -> Object.
To simplify the process of serialization and deserialization, Salesforce has provided a whole class for this purpose, i.e. JSONParser Class.
In below a callout was made to web service and it returned a response in JSON format. Then the response is parsed to get all the totalPrice field values and get the grand total.
public class JSONParserUtil {
@future(callout=true)
public static void parseJSONResponse() {
Http httpProtocol = new Http();
HttpRequest request = new HttpRequest();
String endpoint = ‘https://docsample.herokuapp.com/jsonSample’;
request.setEndPoint(endpoint);
request.setMethod(‘GET’);
HttpResponse response = httpProtocol.send(request);
System.debug(response.getBody());
// 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);
}
}
Example: Parse a JSON String and Deserialize It into Objects, for this example we are taking a hardcoded JSON String and the entire string is parsed into Invoice objects using the readValueAs method.
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());
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;
}
Another way to do deserialization is as below.
Invoice inv = (Invoice)JSON.deserialize(jsonStr, Invoice.class);
This will convert a the response string into a single Invoice object. But what if we want to deserialise a list of Invoice object. In this case we will use the below code to deserialise the list
List<invoice> lstInvoice = (list<invoice>) JSON.deserialize(jsonStr list<invoice>.class);
This will parse the string into the respected object list we created in our apex class.
This approach seems easy but it is always better to use the JSONParser Class to serialize and deserialize the object/object list
The post How to do JSON Parsing of a wrapper class in Salesforce appeared first on Salesforce Next Gen.
]]>The post Custom settings appeared first on Salesforce Next Gen.
]]>They are similar to a custom object, it enables a user to create custom data, make an association between them similar to the custom object. The difference is that the custom settings are exposed in the application cache, this data can then be efficiently accessed without querying the database and reduce the overall overhead at the server and improves the efficiency of the App. The custom setting can be used with validation rule, apex class or formula fields etc.
There are two types of custom settings:
List Custom setting provides a reusable set of static data, we can put frequently access data in the custom setting and this can be accessed without SOQL query to the database. Data in list custom setting does not change with profile or user and is available throughout the organization.
Hierarchy custom setting is based on organization’s hierarchy profile logic and is not available throughout the organization. It checks the context of the user for its profile, organization and then returns the lowest value.
The custom setting can be created from UI of Salesforce and can be managed after creating the setting.
Custom Setting methods
These methods are all instance specific methods, they are called and operate by a particular instance of the custom setting. Custom methods are divided based on the type custom setting we are accessing.
List Custom Setting Methods
The following are instance methods are used to fetch values from list custom settings.
Hierarchy Custom setting methods
The following are instance methods are used to fetch values from Hierarchy custom settings.
7. Custom Setting in Salesforce
The post Custom settings appeared first on Salesforce Next Gen.
]]>