0

I have a custom object Parent__c and a Master-Detail relationship with Child__c. I've been writing various InvocableMethods that use JSON.serialize() to send data to an external API (that I control, BTW). Works great. The invocable receives the object itself Parent__c, making the code really simple.

But it appears that the children are not serialized at all, which probably makes sense.

What is the best practice to do this? Any tips or ideas?

2

In the invocable, using the parent object, requery for the parent and child, then serialize

 String body = JSON.serialize([SELECT Id, ...,
                 (SELECT Id, ... FROM Children__r)
                    FROM Parent__c 
                    WHERE Id = :invocableParentObject.Id]);
2
  • That is a possible approach, but you end up with a tabular JSON representation, requiring more work on the API end. Sep 25 '20 at 17:37
  • OK, but deserializing into an object with a list of children objects should be trivial on receiving side; I can't evaluate of course the specifics of your requirements
    – cropredy
    Sep 25 '20 at 21:40
1

Turn it into a map or use a wrapper class kinda like this:


public class ResponseWrapper{
  public Object parent;
  public List<Object> children;
  
  public ResponseWrapper(sObject__c myObject){
    parent = myObject;
    if(
      myObject.children__r != null
      myObject.children__r.size() > 0
    ) {
      children = myObject.children__r;
    }
  }
}

// in main
ResponseWrapper rw = new ResponseWrapper(myObject);

JSON.serialize(rw,true);
2
  • When a Parent__c object is passed to my method in a Flow action, it seems there is no Children property present at all. I'm using the "Child Relationship Name". Won't even compile. Am I missing something? Sep 25 '20 at 18:40
  • You need to query the children's properties as they are not present in your instantiated model. Whatever fields you explicitly send will be present but you need to get the children's properties from a query as @cropredy suggested. Oct 1 '20 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.