1

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

4
  • 3
    Seeing the code you've tried so far would be helpful (along with any error messages you're getting), though I do have an educated guess. SObject's .get() method returns an Object, which is nearly useless on its own. You really need to do an explicit type-cast to make the result useful (so like String name = (String)rec.get('Name');)
    – Derek F
    Commented Jan 28, 2022 at 22:32
  • 2
    if you deserialize into a Work_Order_Product__c object you can access the fields using dot notation - like myWorkProduct.Name
    – cropredy
    Commented Jan 28, 2022 at 22:55
  • 2
    Might be similar to this issue.
    – Adrian Larson
    Commented Jan 29, 2022 at 5:13
  • 1
    Are you sure the o/p is from the same record you're trying to access. Few of the records might not have relationship field populated & so they'll always return null. It is similar to contact.Account.Name when contact.AccountId is null. Commented Jan 29, 2022 at 7:10

1 Answer 1

0

My struggle turned out to be related to an earlier question of mine: sObject - converting plural to singular?

By converting my objNames to their singular variety, I was able to pluck the targeted fields - thanks!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .