function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lakshmi PalnatiLakshmi Palnati 

Can I create a custom field with datatype as sobject in the platform event?

In the platform event, I only see custom field datatypes with Text, Date, Checkbox and Number, but not an sobject type. I need to serialize my own class instance (which has accounts + contact list) and publish the object in json format.

I tried creating a custom text field (with name data__c) and assigned the  json serialized object to this field. But, the receiver side is getting the unnecessary quote since it's a string. I want to avoid that and just publish as an object only, can I do that?
// custom classes defined for json serialization
    class CustomAccount {
        String oper;
        List<Account> accountList;
        List<CustomContact> custContactList;       
    }
// creating an object 
customAccount ca = new CustomAccount();

// My new platform event, with assigning the json serialized data to data__c which a text field
Pltf_Notifications__e eve = new Pltf_Notifications__e();

eve.data__c = json.serialize(ca);
Now, at the receiver side the data__c is coming like start and ends with double quotes instead of just an object (which starts with curly brackets) like as follows:

User-added image

So one option is the receiver should take this quotes out and treat this as an object or other option sending it like an object itself. Request is, can we send as an object? Please help me here.

Thanks
ShivankurShivankur (Salesforce Developers) 
Hi Lakshmi,

You can't create sobject data type for platform events. You can handle the logic from platform trigger if response has sobject type by deserializing the sobject data type. If it matches, you can call other handler classes from here by passing the sobject data and construct your desired format from here, then fires the platform event.

Hope above information helps, Please mark as Best Answer so that it can help others in the future.

Thanks.
Lakshmi PalnatiLakshmi Palnati
Hi Shivankur,
Thank you for the response! But, platform event trigger is "After Insert" only, so that means the event message should have already been delivered to the EventBus before calling the trigger, so we can't modify anything there right? The problem here is, since we want to publish the "CustomAccount" object (it's a blob with repeated account/contact objects) without serializing (otherwise subscriber is seeing the double serialization for my data, since SF is already doing the serialization before inserting into the EventBus).
So, before firing the platform event, how do we include this customAccount object to the subscribers without long-text field?