Given the following output for JSON.serializePretty(record) :
{
"attributes" : {
"type" : "Work_Order_Product__c",
"url" : "/services/data/v54.0/sobjects/Work_Order_Product__c/a0c750000000aVmAAI"
},
"Work_Order__c" : "a0675000000ELPfAAO",
"Id" : "a0c750000000aVmAAI",
"Product__c" : "01ta00000040BcjAAE",
"Product__r" : {
"attributes" : {
"type" : "Product2",
"url" : "/services/data/v54.0/sobjects/Product2/01ta00000040BcjAAE"
},
"Name" : "Widget",
"Id" : "01ta00000040BcjAAE"
}
}
.. how do I retrieve the value from "Name" (Widget), above? All my combos of getSObject and get seem to fail.
EDIT: Code, as requested:
Note, I expect most results to fail (and return null thanks to the catch block) - problem is, the record I'm expecting success.. yep - also returns null). Here she is :
private Object getValue(List<SObject> records, String path) { //Work_Order_Products__r.Product__r.Name
for(sObject record : records) {
SObject temp = record;
String[] parts = path.split('\\.');
try {
while(parts.size() > 1) {
temp = temp.getSObject(parts.remove(0));
}
return temp.get(parts[0]);
} catch(Exception e) {
continue;
}
}
return null;
}
Thank you kindly
.get()
method returns anObject
, which is nearly useless on its own. You really need to do an explicit type-cast to make the result useful (so likeString name = (String)rec.get('Name');
)Work_Order_Product__c
object you can access the fields using dot notation - likemyWorkProduct.Name
relationship
field populated & so they'll always returnnull
. It is similar tocontact.Account.Name
whencontact.AccountId is null
.