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