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 Salesforce Interview Questions and Answers Part 1 appeared first on Salesforce Next Gen.
]]>A. Salesforce is a Cloud based software made on Force.com platform, it has a pre-built feature to serve as a CRM, but Salesforce is not limited to be called CRM, It has many out of the box features. Salesforce uses Multitenant architecture
2. What is Multitenancy?
A. It is the methodology in which all users share IT related resources to make it cost effective even for a small business. It helps in reducing the initial cost of starting a new.
Images sourced from site https://developer.salesforce.com/page/Multi_Tenant_Architecture
3. Can you explain multi-tenant Data model?
A. To deal with a tremendous, constantly changing arrangement of the genuine database, Force.com implements it storage model with the help of metadata, data and pivot table as described in the diagram below.
Images sourced from site https://developer.salesforce.com/page/Multi_Tenant_Architecture
4. Describe an object in Salesforce? How many types of objects are there in Salesforce?
A. They are similar to database tables of an organization and are used to store a record in Salesforce. Salesforce has provided us with some predefined objects which are known as standard objects and Salesforce has provided us with the ability to create new objects which are known as the Custom object.
5. What is the distinguishing factor between the standard object and custom object?
A. API name of Custom objects contains a suffix of ‘__c’. It is added automatically by Salesforce. E.g customobjectName__c
6. What is a field and how many types of field are there in Salesforce?
A. There are 4 types of fields, 1) Compound Field 2) system Field 3) required Field 4) custom field
7. What is a relationship field in Salesforce and how many types of relationships are there in Salesforce?
A. A relationship field is the one which associates one object with another object. A relationship can be formed between standard objects, custom objects and also between custom and standard objects. Salesforce provides three type of relationships, 1) Lookup 2) Master-Detail Relationship 3) External Relationship, the first two are the most common relationship used throughout the Salesforce.
8. The difference between lookup and master-detail relationship?
A. There are fundamental differences in the behavior and record sharing that you need to read up on.
The most important difference is that master-detail has a direct dependency between the objects:
You cannot have a detail record without a master.
The detail record inherits sharing rules from the master.
The maximum number of master-detail relationships are limited to two.
All related detail objects are deleted if the master object is deleted.
Lookups are used when the behavior of the master-detail – particularly around sharing rules, profile permissions and cascade delete are not required.
when multiple parents need to be referenced then we use look-up
9. Define Self Relationship in Salesforce?
A. It is a look up Relation to the same object.
10. How many types of Object Relationships are supported by Salesforce?
A. Salesforce supports three types of object relationship: 1) one -to- one 2) one – to – many 3) many – to – many
11. What is a trigger, when do we use before and after trigger?
A. A trigger is the flow of code which initiates before or after a DML Event. i.e. before insert or after update etc. We use before trigger if we want to process data before the record is committed and after trigger where we want to use the values from the committed record to change the value in other object’s record.
Salesforce interview Questions based Apex Collections
Apex Collections are set of identical elements grouped together in a collection. A collection can be of three types list, set and map. Interview related questions as per the ones which I have faced during my interviews.
Q.What are the types of collections which are supported by salesforce?
A. Salesforce supports three types of collections
Q. What are the difference between list, set and maps?
A. There are many differences between these collections.
Q. what is the difference between add() and addAll() method?
A add() is used to add only one element in the collection and addAll() is used to add a collection to another similar collection.
Q. how to check whether a list is null or empty?
A. We check a list is empty or null by checking following condition/
If((listObj != null)&&(list.size()>0))
****More Questions to come
Next: Salesforce Interview Question and Answers Part 2
The post Salesforce Interview Questions and Answers Part 1 appeared first on Salesforce Next Gen.
]]>