Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Extract nested attribute value from JSON String using Apex

Salesforce offers two main ways to extract values from a JSON string
1) JSON.deserialize() This approach requires you to have a wrapper class/other valid entity to deserialize the data to.
2) JSON.createParser(jsonString) This approach requires you to loop through a bunch of confusing parser.nextToken() calls

In this article I am introducing an easy to use utility to extract inner attribute values from any JSON string. This is leveraging JSON.createParser(). But once you have this utility, you don't have to go through the parser.nextToken() confusion.

Example of use
Utils.extractAttributeFromJson('{"data":{"user":{"organization":{"id":"123"}}}}', 'data.user.organization.id');


Please note that it will be more performant to use JSON.createParser() directly if you have multiple attributes to extract from the JSON.

Using curl to authenticate to Salesforce REST API

If you are building an application that needs to connect to Salesforce, there are multiple ways you can do this. Same is true for authenticating against Salesforce also. You have a wide variety of methods available to authenticate against Salesforce. You can find details of different methods using OAuth in below link.

Authenticating apps with OAuth 

Salesforce REST API, provides an efficient way to access Salesforce data. It is common to use this API from mobile apps. In this article we will have a look about how to authenticate and access data using REST API. You can use this same process to authenticate mobile/desktop applications. To demonstrate this, we are using a tool cURL. This tool is preinstalled in Mac. If you are using a windows PC, go to cURL download page and install this application. Once you have installed this tool, you can make http requests with custom headers and JSON body from terminal or command line.

There are different ways to authenticate your application against connected app in Salesforce like “Web Server OAuth flow”, User Agent OAuth flow”, “Username-password flow” etc. We are going to use OAuth 2.0 Username-Password flow here.

Authentication and data operations

1) Create a connected app in Salesforce

    First you need to create a connected app in Salesforce. You can do this by going to “Create => Apps => Connected Apps => New” under setup. Fill in the details and save. UI will looks like below image,

image

2) Note down Consumer Key and Consumer Secret 

    Once you have saved your details, you will be able to get “Consumer Key” and “Consumer Secret” under “API(Enable OAuth Settings)” section. Note down the values. You need to use these values while authenticating against Salesforce.

3) Authenticate to get session token 

    First step of authentication is to get session token using username, password, customer key and customer secret. This is obtained by making http request to “https://login.salesforce.com/services/oauth2/token” or “https://test.salesforce.com/services/oauth2/token” for production and sandboxes respectively using cURL. If the authentication is success, it will return a session token/access token. You can make subsequent API calls using this token. This step will look like below,

4) Do REST operations – Query/Insert/Update/Delete etc 

    Once you have access token you can make different REST API calls. All API calls should go to the instance URL returned by login call. Also access token obtained in login call should be added as “Authorization” header parameter. You can find examples of query, insert, update and delete operations below,

Summary

    Now you should have a good idea of how to authenticate your mobile/desktop application against Salesforce using username-password OAuth flow and do operations using REST API. If you are not comfortable using cURL from command line for trying this process, same steps can be done through browser extensions/chrome apps like “Advanced REST Client” or “Postman”.

How to create visualforce page using Streaming API

Streaming API allows to push data (whenever records are created or updated in the backend) to a visualforce page opened by a user without refreshing page. It is very much similar to push notifications in mobile apps. You can refer Streaming API developer guide to get additional details regarding streaming API. Since it is an API in Salesforce, you can connect to it using multiple ways. You can build a java client application to connect to Salesforce. In this post, we will cover how to create a visualforce page using streaming API. This page will show newly created opportunities without reloading the page.

Steps to Use

1) Create a push notification in Salesforce

    Streaming API works on the model of subscribing to push notifications. So first step is to create a push notification at the salesforce end to which we can subscribe from the visualforce page we are going to create. In this post we will create a push notification on opportunity object. Easiest way to create this is execute below code in developer console,

2) Create visualforce page and controller to subscribe to this push notification

    Cometd JavaScript library is used to get data in JSON format to visualforce page. Then using this JavaScript data can be rendered to visualforce page. In the example given below, controller queries 10 opportunity records and displays as a table in page level. Thereafter whenever new opportunities are created in the backend, streaming API pushes data as JSON to page and using JavaScript this data is appended at the end of the table.


 

In the page a static resource is used with JavaScript libraries like cometd, JSON2 etc. You can find the static resource in Salesforce Sample Codes Github project.

Please note that streaming API usage is counted against a 24hour daily limit. Exact limit varies with edition of salesforce. For developer edition it is 10000 in 24 hours.

How to build autocomplete fields in visualforce pages

It is a very handy option to have autocomplete in picklists/dropdowns with large number of options. In this blog we will cover how to use a multiselect autocomplete field in a visualforce page. image

In this example we will display a list of email addresses configured in a custom setting as autocomplete options in an input field. It will also demonstrate how to pass the value that user is selecting to the controller.

It works based on jQuery UI autocomplete feature. Necessary css and JavaScript is available in CDN. you can find links to these CDN files in the visualforce page code.

Steps to Use

1) Create a custom setting and create records

   In this example, the list of email addresses that are displayed in autocomplete is pulled from name field in a custom setting. Please create a list custom setting with name AutocompleteEmails(AutocompleteEmails__c). Then create some email addresses as entry in the custom setting.

2) Create a page and controller

   Code used for achieving it can be found below,

 

   In the constructor of the class, email addresses are queried from the custom setting. Then these values are converted to JSON. This JSON file is assigned to a property in the controller, which is accessible in the page. Then in page level, using this JSON, autocomplete feature is created. Since <apex:inputText does not support applying autocomplete feature on it, autocomplete is created in a regular input field. The values that user select in this regular input is passed to controller using an <apex:inputHidden field. In the save method, this value is passed to controller and it is printed using a System.debug() statement.

Usage

This feature will be very useful when users are using a dropdown with large number of options in a visualforce page. This will help users to find the value they are searching for very easily.