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: Dynamic SOQL Chapter 3 contd. appeared first on Salesforce Next Gen.
]]>Now in the previous post, we were able to fetch the fields related to an sObject at the run time and we used string o create a structured query according to the SOQL syntax. Below is the complete code where I have selected an sObject at run time and found its field and fetched a list of sObject.
When it comes to displaying this list of sObject on the Visualforce page, then it becomes little tricky. As we know that to print on the Visualforce page we need to know the field of the sObject before hand, therefore, the regular way of displaying the table is out of the question.
To overcome this issue, we created a list of string as well while we created the query string for the database.query() method. With help of this, we were able to display all the fields fetched at the run time. As we find in SQL.
Below is the complete code :-
Apex:
public class PostTestingClass {
public list<sObject>sObjectList {get;set;}
public list<string> FieldNameForTable1{get;set;}
public list<string> FieldNameForTable{get;set;}
public list<selectoption> fieldList {
get{return findTheFields();}
set;}
public boolean resultTableVisible {get;set;}
public string selectedObject = ‘sfng__ob1__c’;
public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe(); // Org Map
public string queryString {
get{
FieldNameForTable = new list<string>();
string finalQueryString = ‘select ‘ ;
for(SelectOption s:fieldList){
finalQueryString = finalQueryString + s.getValue() + ‘,’;
FieldNameForTable.add(s.getValue());
}
finalQueryString = finalQueryString.removeEnd(‘,’);
finalQueryString += ‘ from ‘ + selectedObject;
return finalQueryString ;}
set;
}
public PostTestingClass(){resultTableVisible = false;}
public list<selectoption> findTheFields(){
list<selectoption> fieldList1 = new list<selectoption>();
Map<String, Schema.SObjectField> schemaFieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : schemaFieldMap.Values()){
schema.describefieldresult dfield = sfield.getDescribe();
fieldList1.add(new SelectOption(dfield.getname(),dfield.getlabel()));
}
return fieldList1;
}
public void fetchResultOfQuery(){
resultTableVisible = true;
sObjectList = new list<sObject>();
FieldNameForTable1 = new list<string>();
system.debug(‘queryString — > ‘ + queryString);
sObjectList = database.query(queryString);
for(string s: FieldNameForTable){
s = s.replace(‘ ‘, ”);
FieldNameForTable1.add(s);
}
system.debug(‘FieldNameForTable1 — > ‘ + FieldNameForTable1);
}
}
Visual Force Code:-
<apex:page controller=”PostTestingClass” >
<apex:form >
<apex:pageBlock >
<apex:selectList size=”1″>
<apex:selectOptions value=”{!fieldList}”></apex:selectOptions>
</apex:selectList><br/><br/><br/>
<apex:inputTextarea value=”{!queryString}” /><br/>
<apex:commandButton action=”{!fetchResultOfQuery}” value=”Search” />
</apex:pageBlock>
<apex:pageBlock id=”resultTable” rendered=”{!resultTableVisible}”>
<apex:outputPanel >
<apex:pageBlockTable value=”{!sObjectList}” var=”records”>
<apex:repeat value=”{!FieldNameForTable1}” var=”fields”>
<apex:column value=”{!records[fields]}”></apex:column>
</apex:repeat>
</apex:pageBlockTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
Next, I will show you how to implement all of this in a small project which works just as SOQL Query builder of WorkBench.
Next: Salesforce Interview Questions and Answers Part 1
The post Salesforce: Dynamic SOQL Chapter 3 contd. appeared first on Salesforce Next Gen.
]]>The post Salesforce: Dynamic SOQL Chapter 3 appeared first on Salesforce Next Gen.
]]>So in the previous post, we have learned how to get all sObjects and its related field in the runtime. Feel free to play around with the describe calls and describe result classes, next we are going to learn how to make a dynamic SOQL and display the result of the same on a Visualforce page.
To make a dynamic SOQL we need a sObject, its field and that too in a proper format. We know that to use “[select … From object]”, we need to beforehand what is the type of sObject, because it returns a list of specific sObjectType. To overcome this we use another method of Database class i.e. “Database.query();”.
public class PostTestingClass {
public list<selectoption> fieldList {
get{return findTheFields();}
set;}
public string selectedObject = ‘account’;
public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe(); // Org Map
public string queryString {
get{
string finalQueryString = ‘select ‘ ;
for(SelectOption s:fieldList){
finalQueryString = finalQueryString + s.getValue() + ‘,’;
}
finalQueryString = finalQueryString.removeEnd(‘,’);
finalQueryString += ‘ from ‘ + selectedObject;
return finalQueryString ;}
set;
}
public list<selectoption> findTheFields(){
list<selectoption> fieldList1 = new list<selectoption>();
Map<String, Schema.SObjectField> schemaFieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : schemaFieldMap.Values()){
schema.describefieldresult dfield = sfield.getDescribe();
fieldList1.add(new SelectOption(dfield.getname(),dfield.getlabel()));
}
return fieldList1;
}
}
In the code above we take the value of sObject dynamically, then we find the related fields of the objects and then using the values we make query string according to the syntax of SOQL. Now we can use this query to fetch the list of sObjects using the database.query() method.
Visualforce page: –
<apex:page controller=”PostTestingClass” >
<apex:form>
<apex:pageBlock>
<apex:selectList size=”1″>
<apex:selectOptions value=”{!fieldList}”></apex:selectOptions>
</apex:selectList><br/><br/><br/>
<apex:inputTextarea value=”{!queryString}” />
</apex:pageBlock>
</apex:form>
</apex:page>
Next: Salesforce: Dynamic SOQL Chapter 3 contd.
The post Salesforce: Dynamic SOQL Chapter 3 appeared first on Salesforce Next Gen.
]]>