Demystifying Salesforce REST API Part 2: Parsing JSON in Salesforce
let us have a look at sampleJSON response from the HTTP request we have created in Salesforce Rest API Integration Part 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | { "results": [{ "gender": "male", "name": { "title": "mr", "first": "luis", "last": "mora" }, "location": { "street": "5004 calle de arturo soria", "city": "talavera de la reina", "state": "región de murcia", "postcode": 47623 }, "email": "luis.mora@example.com", "login": { "username": "greenbird173", "password": "bones", "salt": "Z0InytVP", "md5": "4133a147e63fd1cacaa11c107157bbd9", "sha1": "59a07b0a9f5209153e15e7cd6f9ed44e5853b547", "sha256": "d85f0d7241c09bc1044b923b55f2eaa8f7b4805208dd001294b23e83d6af51de" }, "registered": 1218507830, "dob": 1196943294, "phone": "952-069-556", "cell": "655-704-166", "id": { "name": "DNI", "value": "03541125-Y" }, "picture": { "large": "https://randomuser.me/api/portraits/men/6.jpg", "medium": "https://randomuser.me/api/portraits/med/men/6.jpg", "thumbnail": "https://randomuser.me/api/portraits/thumb/men/6.jpg" }, "nat": "ES" }], "info": { "seed": "500c13f32b0e719c", "results": 1, "page": 1, "version": "1.0" } } |
Step 1: Understanding JSON
In JSON each curly braces enclosure represents a object which is represented in Apex by a inner or wrapper class. Each Square braces represents an array which is a list or array in Apex. For parsing JSON in Apex we have to recreate entire structure in Apex using inner class.
Step 2: Creating a JSON wrapper
Complete JSON Apex Wrapper for the above JSON data structure will look like.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | public class data{ public list results {get;set;} public info info{get;set;} } //result object wrapper public class result{ public string gender{get;set;} public Name name{get;set;} //Name Object public Location location {get;set;} //Location Object Public string email{get;set;} public Login login {get;set;} Public Integer registered{get;set;} Public Integer dob{get;set;} Public string phone{get;set;} Public string cell{get;set;} Public Id1 ido{get;set;} Public picture picture{get;set;} Public string nat{get;set;} } //Name Object Wrapper public class Name{ Public string title{get;set;} Public string first{get;set;} Public string last{get;set;} } //Location Object Wrapper public class Location{ Public string street{get;set;} Public string city{get;set;} Public string state{get;set;} Public string postcode{get;set;} } public class Picture{ Public string large{get;set;} Public string medium{get;set;} Public string thumbnail{get;set;} } public class Id1{ Public string name{get;set;} Public string value{get;set;} } public class Login{ Public string username{get;set;} Public string password{get;set;} Public string salt{get;set;} Public string md5{get;set;} Public string sha1{get;set;} Public string sha256{get;set;} } public class info{ Public string seed{get;set;} Public Integer results{get;set;} Public string page{get;set;} Public string version{get;set;} } |
Step 3: Parsing JSON
Salesforce provides JSONParser class,by using the same we will parse the JSON as below.
1 2 3 4 5 6 7 8 9 10 11 | //Parse Json from response JSONParser parser = JSON.createParser(JSONresponse); while (parser.nextToken() != null) { if (parser.getCurrentToken() == JSONToken.START_OBJECT) { // Read entire JSON object, including its array of items. UserData = (data)parser.readValueAs(data.class); system.debug( UserData); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | Public class FetchUserData{ public Data UserData{get;set;} public String JSONresponse{get;set;} Public pageReference RefreshUserData(){ //Create Request Http httpProtocol = new Http(); HttpRequest request = new HttpRequest(); //End point will be your rest service URL String endpoint = 'https://randomuser.me/api/'; request.setEndPoint(endpoint); request.setMethod('GET'); //Get response HttpResponse response = httpProtocol.send(request); JSONresponse = response.getBody(); system.debug(JSONresponse); //Parse Json from response JSONParser parser = JSON.createParser(JSONresponse); while (parser.nextToken() != null) { if (parser.getCurrentToken() == JSONToken.START_OBJECT) { // Read entire JSON object, including its array of items. UserData = (data)parser.readValueAs(data.class); system.debug( UserData); } } return null; } //Wrapper classes for creating JSON structure start here public class data{ public list results {get;set;} public info info{get;set;} } //result object wrapper public class result{ public string gender{get;set;} public Name name{get;set;} //Name Object public Location location {get;set;} //Location Object Public string email{get;set;} public Login login {get;set;} Public Integer registered{get;set;} Public Integer dob{get;set;} Public string phone{get;set;} Public string cell{get;set;} Public Id1 ido{get;set;} Public picture picture{get;set;} Public string nat{get;set;} } //Name Object Wrapper public class Name{ Public string title{get;set;} Public string first{get;set;} Public string last{get;set;} } //Location Object Wrapper public class Location{ Public string street{get;set;} Public string city{get;set;} Public string state{get;set;} Public string postcode{get;set;} } public class Picture{ Public string large{get;set;} Public string medium{get;set;} Public string thumbnail{get;set;} } public class Id1{ Public string name{get;set;} Public string value{get;set;} } public class Login{ Public string username{get;set;} Public string password{get;set;} Public string salt{get;set;} Public string md5{get;set;} Public string sha1{get;set;} Public string sha256{get;set;} } public class info{ Public string seed{get;set;} Public Integer results{get;set;} Public string page{get;set;} Public string version{get;set;} } //End of Wrapper Classes } |
Step 4: Displaying rendered JSON in Visualforce
Let us see how to get the data from Wrapper classes and Display the same in VisulForce Page. Here we a refresh button where user can refresh the data on screen
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <apex:page controller="FetchUserData"> <apex:commandButton action="{!RefreshUserData}" value="Refresh data" reRender="weatherpanel" /> <apex:pageBlock title="User details" id="weatherpanel"> <apex:pageBlockSection collapsible="false" title="General details" > <apex:outputText label="Name" value="{!UserData.results[0].name.title} {!UserData.results[0].name.first} {!UserData.results[0].name.last}"> <apex:outputText label="Gender" value="{!UserData.results[0].gender}"> <apex:outputText label="Email" value="{!UserData.results[0].email}"> <apex:outputText label="Phone" value="{!UserData.results[0].phone}"> <apex:outputText label="Cell" value="{!UserData.results[0].cell}"> <apex:outputText label="Address" value="{!UserData.results[0].location.street} {!UserData.results[0].location.city} {!UserData.results[0].location.state} {!UserData.results[0].location.postcode}"> |
JSON2APEX
Json2Apex tool will help generate strongly typed Apex code for parsing a JSON structure given an example of the JSON. Using this all the manual job of creating wrapper classes can be eliminated.
No comments:
Post a Comment