Friday, October 17, 2014

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 I
JSON Parsing with Apex in Salesforce - Part II

So 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 parsing
public 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 "Parse Multiple JSON Data" button, it parsed the JSON data and displayed in tabular format like below-

If you have any feedback, please share with me. Thanks in advance.

0 comments:

Post a Comment