Deprecated: Optional parameter $list declared before required parameter $is_script is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php on line 21

Deprecated: Optional parameter $register declared before required parameter $footer_or_media is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php on line 45

Deprecated: Optional parameter $register declared before required parameter $footer_or_media is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php on line 104

Deprecated: Optional parameter $expire declared before required parameter $path is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_functions.php on line 54

Deprecated: Optional parameter $depth declared before required parameter $output is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/themes/entaro/inc/classes/megamenu.php on line 155

Deprecated: Optional parameter $depth declared before required parameter $output is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/themes/entaro/inc/classes/mobilemenu.php on line 147

Deprecated: Optional parameter $args declared before required parameter $wp_customize is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/extensions/customizer/extension_customizer.php on line 583

Deprecated: Optional parameter $args declared before required parameter $wp_customize is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/extensions/customizer/extension_customizer.php on line 606

Warning: Cannot modify header information - headers already sent by (output started at /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php:21) in /home1/oijoiv2f/public_html/wp-includes/feed-rss2.php on line 8
Salesforce: Dynamic SOQL Chapter 3 Archives - Salesforce Next Gen https://salesforcenextgen.com/tag/salesforce-dynamic-soql-chapter-3/ Trailhead and Beyond Mon, 28 Dec 2020 19:46:31 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.4 https://salesforcenextgen.com/wp-content/uploads/2020/10/cropped-76dc0dd6-326a-4956-a412-bfdf20c7fb23_200x200-32x32.png Salesforce: Dynamic SOQL Chapter 3 Archives - Salesforce Next Gen https://salesforcenextgen.com/tag/salesforce-dynamic-soql-chapter-3/ 32 32 How to do JSON Parsing of a wrapper class in Salesforce https://salesforcenextgen.com/how-to-do-json-parsing-of-a-wrapper-class-in-salesforce/ https://salesforcenextgen.com/how-to-do-json-parsing-of-a-wrapper-class-in-salesforce/#comments Mon, 05 Mar 2018 06:02:34 +0000 http://www.salesforcenextgen.com/?p=1240 How to do JSON Parsing of a wrapper class in Salesforce. What is JSON Parsing? 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 …
Continue reading How to do JSON Parsing of a wrapper class in Salesforce

The post How to do JSON Parsing of a wrapper class in Salesforce appeared first on Salesforce Next Gen.

]]>
JSON Parsing SalesforceHow to do JSON Parsing of a wrapper class in Salesforce.

What is JSON Parsing?

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.

JSON Parsing Salesforce

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

Also, Have a look at the below resources:

  1. Best Salesforce Interview Questions book with Apex and Visualforce concept explained

Also, Have a look at the below learning resources:

  1. SOQL (Salesforce Object Query Language)

  2. Apex Trigger Best Practices and the Trigger Framework

  3. Salesforce Interview Question and Answers Part 2

  4. Salesforce Interview Questions on Test Class

  5. Salesforce-lightning-interview-questions-2018

     6. Salesforce Interview Questions Batch Class 

The post How to do JSON Parsing of a wrapper class in Salesforce appeared first on Salesforce Next Gen.

]]>
https://salesforcenextgen.com/how-to-do-json-parsing-of-a-wrapper-class-in-salesforce/feed/ 1
Salesforce: Dynamic SOQL Chapter 3 contd. https://salesforcenextgen.com/salesforce-dynamic-soql-chapter-3-contd/ https://salesforcenextgen.com/salesforce-dynamic-soql-chapter-3-contd/#comments Wed, 05 Jul 2017 14:35:25 +0000 http://salesforcenextgen.com/?p=768 Salesforce: Dynamic SOQL Chapter 3 Contd. 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 …
Continue reading Salesforce: Dynamic SOQL Chapter 3 contd.

The post Salesforce: Dynamic SOQL Chapter 3 contd. appeared first on Salesforce Next Gen.

]]>
Salesforce: Dynamic SOQL Chapter 3 Contd.

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>

Dynamic SOQL result

Next, I will show you how to implement all of this in a small project which works just as SOQL Query builder of WorkBench.

The post Salesforce: Dynamic SOQL Chapter 3 contd. appeared first on Salesforce Next Gen.

]]>
https://salesforcenextgen.com/salesforce-dynamic-soql-chapter-3-contd/feed/ 6
Salesforce: Dynamic SOQL Chapter 3 https://salesforcenextgen.com/salesforce-dynamic-soql-chapter-3/ https://salesforcenextgen.com/salesforce-dynamic-soql-chapter-3/#comments Tue, 04 Jul 2017 15:31:33 +0000 http://salesforcenextgen.com/?p=728 Salesforce: Dynamic SOQL Chapter 3 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 …
Continue reading Salesforce: Dynamic SOQL Chapter 3

The post Salesforce: Dynamic SOQL Chapter 3 appeared first on Salesforce Next Gen.

]]>
Salesforce: Dynamic SOQL Chapter 3

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>

Dynamic SOQL

Next: 

The post Salesforce: Dynamic SOQL Chapter 3 appeared first on Salesforce Next Gen.

]]>
https://salesforcenextgen.com/salesforce-dynamic-soql-chapter-3/feed/ 3