Category: JSON

How to handle JSON data in JavaScript

 JSON (JavaScript Object Notation) is a way to represent data through text. It exists as a String and it supports all the basic data types that are supported by a standard JavaScript object. As per Wikipedia, the definition goes -JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format, and data interchange format, that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value).Reference: https://en.wikipedia.org/wiki/JSONNote – I am putting my JavaScript Developer study notes here. There are two methods that I will be discussing in this post. JSON.parse()This method is used to deserialize or convert a JSON string into a JavaScript object. This is highly used while accessing the external API/server response. In the below example, I am converting a string to a JavaScript object using the parse method. You can use the dot (.) to access the individual items in the object.Code:const jsonString = ` { “name”:”Sudipta Deb”, “country”:”Canada”, “favouriteCars”:[ “Honda”,”BMW” ], “employed”:true } `;const jsonObject = JSON.parse(jsonString);console.log(jsonObject);console.log(jsonObject.name);Output:{ name: ‘Sudipta Deb’, country: ‘Canada’, favouriteCars: [ ‘Honda’, ‘BMW’ ], employed: true}Sudipta DebJSON.stringify() This method is used to serialize or convert a JavaScript object into a JSON string. This is highly used before transferring data to an external API/server. In the below example, I am converting the above JavaScript object to a string using the stringify method. Code:const jsonString = ` { “name”:”Sudipta Deb”, “country”:”Canada”, “favouriteCars”:[ “Honda”,”BMW” ], “employed”:true } `;const jsonObject...

Read More

JSON Parsing with Apex in Salesforce – Part III

Hello friends,In this post, I am going to share the information how to parse multiple JSON request and display the same in Visual Force page in tabular format.If you haven’t visited my previous posts regarding JSON parsing, please go to below links -JSON Parsing with Apex in Salesforce – Part IJSON Parsing with Apex in Salesforce – Part IISo let’s start.First the Visual Force Page-<apex:page controller=”CountryController”> <apex:form > <apex:pageBlock Title=”JSON Parser Example – Multiple Data”> <apex:commandButton value=”Parse Multiple JSON Data” action=”{!parseJSONData}” reRender=”countryData” /> </apex:pageBlock> <br /> <apex:pageBlock id=”countryData”> <apex:pageBlockTable value=”{!countries}” var=”country”> <apex:column headerValue=”Country Name” value=”{!country.countryName}”/> <apex:column headerValue=”Country Capital” value=”{!country.countryCapital}”/> <apex:column headerValue=”Country Currency” value=”{!country.countryCurrency}”/> </apex:pageBlockTable> </apex:pageBlock> </apex:form></apex:page>Now the controller-public class CountryController { private List<CountryDataWrapper> countryDataWrapper; public void parseJSONData(){ countryDataWrapper = new ParseMultipleJsonData().parse(); } public List<CountryDataWrapper> getCountries(){ return countryDataWrapper; }}The wrapper class to hold Country information-public class CountryDataWrapper { public String countryName{get;set;} public String countryCapital{get;set;} public String countryCurrency{get;set;}}And finally the parser class doing the parsingpublic class ParseMultipleJsonData { public List<CountryDataWrapper> parse() { String jsonMessage = ‘[{‘+ ‘ “countryName”: “India”,’+ ‘ “countryCapital”: “Delhi”,’+ ‘ “countryCurrency”: “Indian rupee”‘+ ‘},’+ ‘{‘+ ‘ “countryName”: “Switzerland”,’+ ‘ “countryCapital”: “Bern”,’+ ‘ “countryCurrency”: “Swiss franc”‘+ ‘},’+ ‘{‘+ ‘ “countryName”: “United States of America”,’+ ‘ “countryCapital”: “Washington, D.C.”,’+ ‘ “countryCurrency”: “US Dollar”‘+ ‘}]’; return (List<CountryDataWrapper>) System.JSON.deserialize(jsonMessage, List<CountryDataWrapper>.class); }}That’s all. Let’s see how the Visual force page is behaving now-Initially the page looks like -Now when we clicked on the...

Read More

JSON2Apex – Convert JSON Into Apex Class

JSON2Apex is an online tool to convert JSON into Apex class. The URL is: JSON2ApexThis tool is hosted in Heroku.This app allows a user to paste a JSON String, and then this app will generate strongly typed apex code that can deserialize it. This entire app is written in Java using Play framework.A special thanks to superfell and metadaddy for providing this amazing tool.Guys, please use this one while working with JSON and Apex...

Read More

JSON Parsing with Apex in Salesforce – Part II

This post is in continuation of my previous post regarding JSON Parsing.In this post, what I am going to share is-How to parse a little more complex JSON containing array. Once the JSON data is parsed, how to display the same information in Visual Force Page.Check the below link to understand what I am trying to achieve at the end of this posthttp://sudipta-developer-edition.ap1.force.com/studentdetailsSo let’s start with creating the Visual Force Page<apex:page controller=”StudentDetailController”> <apex:form > <apex:pageBlock Title=”JSON Parser Example”> <apex:commandButton value=”Parse JSON Data” action=”{!parseJSONData}” reRender=”studentData” /> </apex:pageBlock> <br /> <apex:pageBlock id=”studentData”> First Name: <apex:inputText value=”{!firstName}” /> Last Name: <apex:inputText value=”{!lastName}” /> <br/> <apex:pageBlockSection title=”Language Known:” collapsible=”false”> <apex:selectList value=”{!selectedLanguage}” multiselect=”false” size=”1″> <apex:selectOptions value=”{!languageOptions}”/> </apex:selectList> </apex:pageBlockSection> </apex:pageBlock> </apex:form></apex:page>Now the controller-public class StudentDetailController{ public String firstName{get;set;} public String lastName{get;set;} public String selectedLanguage{get;set;} private StudentDetailWrapper m; public List<SelectOption> languageOptions; public void parseJSONData(){ m = new ParseStudentData().parseData(); doAllInitialization(); } public void parseJSONData(String jsonMessage){ m = new ParseStudentData().parseData(jsonMessage); doAllInitialization(); } public List<SelectOption> getLanguageOptions(){ if(null == languageOptions){ languageOptions = new List<SelectOption>(); } return languageOptions; } private void doAllInitialization(){ initializeStudentName(); initializeLanguageOptions(m.language); } private void initializeStudentName(){ this.firstName = m.firstName; this.lastName = m.lastName; } private void initializeLanguageOptions(List<String> language){ languageOptions = new List<SelectOption>(); for(String aLanguage : language){ languageOptions.add(new SelectOption(aLanguage, aLanguage)); } }}Now the class which will do the JSON Parsing-public class ParseStudentData { private StudentDetailWrapper m; public StudentDetailWrapper parseData(String jsonMessage){ return doParsing(jsonMessage); } public StudentDetailWrapper parseData(){ String jsonMessage = ‘{“firstName” : “Sudipta”,...

Read More

JSON Parsing with Apex in Salesforce – Part I

Here, I would like to share an example of very basic JSON parsing with Apex programming language in Salesforce.MainWrapper Class:public class MainWrapper { public Integer studentId; public String studentName; public String address; public MainWrapper(Integer studentId, String studentName, String address) { this.studentId = studentId; this.studentName = studentName; this.address = address; }}And now the test class to check whether JSON Parsing is working fine or not.@isTestprivate class TestMainWrapper { static testMethod void testJsonParser() { String jsonMessage = ‘{“studentId” : 1, “studentName” : “Sudipta Deb”, “address” : “Kolkata, India”}’; JSONParser parser = JSON.createParser(jsonMessage); MainWrapper m = (MainWrapper)parser.readValueAs(MainWrapper.class); System.assertEquals(1, m.studentId); System.assertEquals(‘Sudipta Deb’, m.studentName); System.assertEquals(‘Kolkata, India’, m.address); }}I will share more complex JSON Parsing very soon. Any feedback is always...

Read More
Loading

Earlier Posts

  • 2024 (18)
  • 2023 (47)
  • 2022 (25)
  • 2021 (35)
  • 2020 (41)
  • 2019 (13)
  • 2018 (16)
  • 2017 (14)
  • 2016 (18)
  • 2015 (74)
  • 2014 (20)