-
-
Save tehnrd/4559623 to your computer and use it in GitHub Desktop.
List<Object> fieldList = (List<Object>)JSON.deserializeUntyped('[{"field":"phone","object":"account"},{"field":"name","object":"account"}]'); | |
for(Object fld : fieldList){ | |
Map<String,Object> data = (Map<String,Object>)fld; | |
//Magic! | |
system.debug(data.get('field')); | |
} |
Here is my total code i had a json in Apex i want to dispplay that json as table forn in salesforce but the list of beds is in mulitple layer so i was confused how to iterate that can you please help me
Thanks in Advance.
My Component
<aura:component controller="BedsData" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickActionWithoutHeader,lightning:availableForFlowScreens" access="global" >
<aura:handler name="init" value="{! this }" action="{! c.init}"/>
<aura:attribute name="values" type="sObject" default="[]"/>
<aura:if isTrue="{!not(empty(v.invests))}">
<aura:iteration items="{!v.values.locations.buildings.beds}" var="item" indexVar="rowIndex">
</aura:iteration>
Room No | Room Name | Gender | Cost |
---|---|---|---|
{!item.roomNo} | {!item.roomName} | {!item.gender} | {!item.cost} |
</aura:if>
</aura:component>
My Controller
({
init: function(component, event, helper) {
let action = component.get("c.bedsData");
action.setParams({});
action.setCallback(this, function(response) {
let state = response.getState();
if (state === "SUCCESS") {
const val= response.getReturnValue();
//console.log('val Response ' +JSON.stringify(val));
component.set("v.values", val);
} else if (status === "INCOMPLETE") {
console.log("No response from server or client is offline.")
} else if (status === "ERROR") {
console.log("Error: " + errorMessage);
}
});
$A.enqueueAction(action);
},
})
BedsDataWrapper
//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//
public class BedsDataWrapper {
public String message;
public Integer responseCode;
public String response;
@AuraEnabled
public List locations;
public class Buildings {
public String buildingName;
public String buildingSite;
@AuraEnabled
public List beds;
}
public class Locations {
public String locationType;
@AuraEnabled
public List buildings;
}
public class Share {
public String roomName;
public String shortRoomName;
}
public class Beds {
@AuraEnabled
public Integer roomNo;
@AuraEnabled
public Integer roomId;
@AuraEnabled
public String roomName;
@AuraEnabled
public String gender;
public String checkinDate;
public String checkOut;
@AuraEnabled
public String cost;
public String appointmentDate;
public Boolean smoking;
public Boolean drinking;
public String roomType;
public String suspendedFromDate;
public String suspendedToDate;
public String buildingName;
public String roomRent;
public Share share;
public String padId;
public String endDate;
}
public static BedsDataWrapper parse(String json) {
return (BedsDataWrapper ) System.JSON.deserialize(json, BedsDataWrapper .class);
}
}
My Apex Class
public class BedsData{
@AuraEnabled
public static BedsDataWrapper bedsData(){
try{
String json = '{"message":"Success","responseCode":4000,"response":"Success","locations":[{"locationType":"HIghway Road","buildings":[{"buildingName":"Ram","buildingSite":"Residencey","beds":[{"roomNo":51,"roomId":2324,"roomName":"Taj Hotel","gender":"M","checkinDate":"11/09/2020","checkOut":"11/16/2020","cost":"1000.00","appointmentDate":"09/16/2021","smoking":false,"drinking":false,"roomType":"100_3","suspendedFromDate":"","suspendedToDate":"","buildingName":"Ram","roomRent":"168313.94685","roomId":2324,"share":{"roomName":"Taj Hotel","shortRoomName":"TH"},"padId":"001","endDate":"99/99/1999"}]}]}]}';';
BedsDataWrapper res= BedsDataWrapper .parse(json);
return res;
} catch(Exception ex){
System.debug('Error occured while fetching the documents list' + ex);
}
return null;
}
}
Hey all! Thanks for keeping this alive. I recently figured it out and forgot to share the solution here. This is what I did:
- Run a sample JSON response through the free, indispensable JSON2Apex Heroku App (do NOT use the "Create explicit parse code" option).
- Deploy the parser and test class to your dev org / sandbox.
For context, here is the JSON2Apex parser class that was automatically generated for me using a sample JSON response. Note that there is also a paired test class, but that doesn't play a factor in here.
// Generated by JSON2Apex http://json2apex.herokuapp.com/
public class J2A_kipuGetOccupancyHigh {
public class Beds {
public String bed_name;
public String enabled;
public String status;
public String gender;
public String gender_identity;
public String casefile_id;
public String first_name;
public String last_name;
public String admission_date;
public String anticipated_discharge_date;
public String dob;
public String level_of_care;
public String program;
}
public class Buildings {
public String building_name;
public List<Rooms> rooms;
}
public class Locations {
public Integer location_id;
public String location_name;
public List<Buildings> buildings;
}
public List<Locations> locations;
public class Rooms {
public String room_name;
public String gender_rule;
public List<Beds> beds;
}
public static J2A_kipuGetOccupancyHigh parse(String json) {
return (J2A_kipuGetOccupancyHigh) System.JSON.deserialize(json, J2A_kipuGetOccupancyHigh.class);
}
}
Let's use my previous example's JSON object structure for the following example: Locations > Buildings > Rooms > Beds.
// first run your raw JSON response through the parsing class (JSON response must be of the string type)
J2A_kipuGetOccupancyHigh jsonApex = J2A_kipuGetOccupancyHigh.parse(jsonRes);
// now create a for loop for each level
for(J2A_kipuGetOccupancyHigh.Locations loc : jsonApex.locations){
// make sure to use the previously created alias each time you go down a level
// do whatever you want for the loc level here
// this is the top level object
for(J2A_kipuGetOccupancyHigh.Buildings bld : loc.buildings){
// do whatever you want for the bld level here
// we are now two levels deeps
for(J2A_kipuGetOccupancyHigh.Rooms rom : bld.rooms){
// do whatever you want for the rom level here
// we are now three levels deep
for(J2A_kipuGetOccupancyHigh.Beds bed : rom.beds){
// do whatever you want for the bed level here
// we are now four levels deep
} // end of bed level
} // end of rom level
} // end of bld level
} // end of loc level and end of entire loop
You may need to make adjustments to this based on the structure of your JSON response, but this is the way I handled it with as little code as possible. The most important thing is to pay attention to the object structure. In another example I had to deal with, the top level was the parent object to 3 laterally related child objects. In that example you would want to use the top level alias for all three of the child for loops, but you also need to make sure that each child is outside of the others' loop since they are on the same level.
I hope this makes sense! Happy coding!
Thank you very much for the solution
@Saitejad7 -- You're welcome!
And do you know how to write aura:if for two different fields
For suppose i had gender in J2A_kipuGetOccupancyHigh class and gender in another class and i want to check if both the gender is same we have to show the dob value or else we have to show dob value as empty like i've tried below but it doesn't work so can you help me out
<aura:if isTrue="{!item.gender== '!val.gender'}">
Unfortunately, I am not familiar with aura. However, in the case of apex, it depends on where the variables are in the hierarchy and where you are trying to make the comparison. Remember that code is read from left to right, top to bottom (this is an overgeneralization -- I understand there is nuance). As such, you want to make sure you are doing your comparison after both variables have been read/created.
Can you drop your code here for reference? I can see that you shared some earlier in the thread, but I'm not seeing where your comparison variables are.
i've been sharing the code but i don't know why all the code is not posting in comment some of the code is not showing in comment
i've been sharing the code but i don't know why all the code is not posting in comment some of the code is not showing in comment
@Saitejad7 -- when you paste your code in the comment, make sure you are putting 3 backquotes before and after the code block so GH recognizes it as code.
"
component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller = "BedsData">
<aura:handler name="init" value="{!this }" action="{!c.init}"/>
<aura:attribute name="bedsWrapper" type="object" />
<div class="slds-p-around--large">
<h1 style="font-size:15px;">
message: {!v.bedsWrapper.message}<br/>
responseCode: {!v.bedsWrapper.responseCode}<br/>
</h1>
<table class="slds-table slds-table--bordered slds-table--cell-buffer">
<thead>
<tr class="slds-text-title--caps">
<th scope="col">
<div class="slds-truncate" title="Room No.">Room No.</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Room Name">Room Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Gender">Gender</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Cost">Cost</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.bedsWrapper.locations}" var="location">
<aura:iteration items="{!location.buildings}" var="building">
<aura:iteration items="{!building.beds}" var="bed">
<tr>
<th scope="row">
<div class="slds-truncate" title="{!bed.roomNo}">{!bed.roomNo}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{!bed.roomName}">{!bed.roomName}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{!bed.gender}">{!bed.gender}</div>
</th>
<th scope="row">
<div class="slds-truncate" title="{!bed.cost}">{!bed.cost}</div>
</th>
</tr>
</aura:iteration>
</aura:iteration>
</aura:iteration>
</tbody>
</table>
</div>
</aura:component>
controller:
({
init: function(component, event, helper) {
var action = component.get('c.bedsData');
//action.setParams({});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var val= response.getReturnValue();
console.log('val Response ' +JSON.stringify(val));
component.set('v.bedsWrapper', val);
} else if (status === "INCOMPLETE") {
console.log("No response from server or client is offline.")
} else if (status === "ERROR") {
console.log("Error: " + errorMessage);
}
});
$A.enqueueAction(action);
}
})
Apex Class:
BedsDataWrapper:
public class BedsDataWrapper{
@AuraEnabled
public String message; //Success
@AuraEnabled
public Integer responseCode; //4000
@AuraEnabled
public String response; //Success
@AuraEnabled
public List<cls_locations> locations;
public class cls_locations {
@AuraEnabled
public String locationType; //HIghway Road
@AuraEnabled
public List<cls_buildings> buildings;
}
public class cls_buildings {
@AuraEnabled
public String buildingName; //Ram
@AuraEnabled
public String buildingSite; //Residencey
@AuraEnabled
public List<cls_beds> beds;
}
public class cls_beds {
@AuraEnabled
public Integer roomNo; //51
@AuraEnabled
public Integer roomId; //2324
@AuraEnabled
public String roomName; //Taj Hotel
@AuraEnabled
public String gender; //M
@AuraEnabled
public String checkinDate; //11/09/2020
@AuraEnabled
public String checkOut; //11/16/2020
@AuraEnabled
public String cost; //1000.00
@AuraEnabled
public String appointmentDate; //09/16/2021
@AuraEnabled
public boolean smoking;
@AuraEnabled
public boolean drinking;
@AuraEnabled
public String roomType; //100_3
@AuraEnabled
public String suspendedFromDate; //
@AuraEnabled
public String suspendedToDate; //
@AuraEnabled
public String buildingName; //Ram
@AuraEnabled
public String roomRent; //168313.94685
@AuraEnabled
public cls_share share;
@AuraEnabled
public String padId; //001
@AuraEnabled
public String endDate; //99/99/1999
}
public class cls_share {
@AuraEnabled
public String roomName; //Taj Hotel
@AuraEnabled
public Integer roomId; //2324
@AuraEnabled
public String shortRoomName; //TH
}
public static BedsDataWrapper parse(String json){
return (BedsDataWrapper) System.JSON.deserialize(json, BedsDataWrapper.class);
}
}
BedsData:
public class BedsData {
@AuraEnabled
public static BedsDataWrapper bedsData(){
try{
String json = '{"message":"Success","responseCode":4000,"response":"Success","locations":[{"locationType":"HIghway Road","buildings":[{"buildingName":"Ram","buildingSite":"Residencey","beds":[{"roomNo":51,"roomId":2324,"roomName":"Taj Hotel","gender":"M","checkinDate":"11/09/2020","checkOut":"11/16/2020","cost":"1000.00","appointmentDate":"09/16/2021","smoking":false,"drinking":false,"roomType":"100_3","suspendedFromDate":"","suspendedToDate":"","buildingName":"Ram","roomRent":"168313.94685","share":{"roomName":"Taj Hotel","roomId":2324,"shortRoomName":"TH"},"padId":"001","endDate":"99/99/1999"}]}]}]}';
BedsDataWrapper results = BedsDataWrapper.parse(json);
return results;
} catch(Exception ex){
System.debug('Error occured while fetching the documents list' + ex);
}
return null;
}
}
"
check the above one...
<aura:if isTrue="{!not(empty(v.values))}">
<div class="slds-table_header-fixed_container slds-scrollable_x" style="height:100%">
<div class="slds-scrollable_y" style="width:1160px">
<table role="grid" aria-rowcount="2" class="slds-table slds-table_header-fixed slds-table_bordered slds-table_edit" style="table-layout:fixed;width:1160px">
<thead>
<tr class="slds-line-height_reset">
<th scope="col" tabindex="-1" aria-label="" style="width:150px">
<div class="slds-cell-fixed" style="width: 150px;outline:none;">
<span class="slds-th__action">
<span class="slds-truncate">Gender</span>
</span>
</div>
</th>
<th scope="col" tabindex="0" aria-label="Name" style="width:100px">
<div class="slds-cell-fixed" style="width: 150px;outline:none;">
<span class="slds-th__action">
<span class="slds-truncate">Name</span>
</span>
</div>
</th>
<th scope="col" tabindex="0" aria-label="Last Name" style="width:100px">
<div class="slds-cell-fixed" style="width: 150px;outline:none;">
<span class="slds-th__action">
<span class="slds-truncate">Last Name</span>
</span>
</div>
</th>
<th scope="col" tabindex="0" aria-label="Name" style="width:100px">
<div class="slds-cell-fixed" style="width: 150px;outline:none;">
<span class="slds-th__action">
<span class="slds-truncate">First Name</span>
</span>
</div>
</th>
<th scope="col" tabindex="0" aria-label="Last Name" style="width:100px">
<div class="slds-cell-fixed" style="width: 150px;outline:none;">
<span class="slds-th__action">
<span class="slds-truncate">DOB</span>
</span>
</div>
</th>
<tbody>
<aura:iteration items="{!v.details}" var="item" indexVar="rowIndex">
<tr data-data="{!rowIndex}">
<td role="gridcell" tabindex="-1" data-label="Record Type Name">
<span class="slds-grid slds-grid_align-spread">
<div class="slds-truncate">
<span class="slds-truncate">{!item.gender}</span>
</div>
</span>
</td>
<td role="gridcell" tabindex="-1" data-label="Record Type Name">
<span class="slds-grid slds-grid_align-spread">
<div class="slds-truncate">
<span class="slds-truncate">{!item.name}</span>
</div>
</span>
</td>
<td role="gridcell" tabindex="-1" data-label="Record Type Name">
<span class="slds-grid slds-grid_align-spread">
<div class="slds-truncate">
<span class="slds-truncate">{!item.lastName}</span>
</div>
</span>
</td>
<td role="gridcell" tabindex="-1" data-label="Record Type Name">
<span class="slds-grid slds-grid_align-spread">
<div class="slds-truncate">
<span class="slds-truncate">{!item.firstName}</span>
</div>
</span>
</td>
<aura:iteration items="{!v.values.result}" var="result" indexVar="rowIndex">
<aura:iteration items="{!result.buildings}" var="buildings" indexVar="rowIndex">
<aura:iteration items="{!buildings.beds}" var="beds" indexVar="rowIndex">
<aura:if isTrue="{!item.gender == '!beds.gender'}">
<td role="gridcell" tabindex="-1" data-label="Record Type Name">
<span class="slds-grid slds-grid_align-spread">
<div class="slds-truncate">
<span class="slds-truncate">{!beds.dob}</span>
</div>
</span>
</td>
<aura:set attribute="else">
<td role="gridcell" tabindex="-1" data-label="Record Type Name">
<span class="slds-grid slds-grid_align-spread">
<div class="slds-truncate">
<span class="slds-truncate">No Dob</span>
</div>
</span>
</td>
</aura:set>
</aura:if>
</aura:iteration>
</aura:iteration>
</aura:iteration>
</tr>
</aura:iteration>
</tbody>
</table>
</div>
</div>
</aura:if>
@dayan-naskar Thank you
After many hours of trying to figure out how to accomplish this..... I found this solution! Thanks a lot
Sick thank you
Worked like a charm! I've spent hours trying different solutions until I came upon this one which is so straightforward! Thank a lot!
Yes i'm trying to recieve that json from apex only ..