Background
I'm working on a project where I'm communicating with an external billing system to create a new Account in our external billing system when a new Account
is created in Salesforce.
Being a billing system, I must include both the Billing and Shipping Addresses (among other information) in the message that I send to the black box, under control of a colleague, that sits between my company's Salesforce org, and our billing system.
Me and my colleague have agreed on using a JSON formatted message for this purpose.
In exploring different methods for constructing my JSON message, I ran across an oddity.
If I query for a composite address field from the Account
, either BillingAddress
or ShippingAddress
, and pass the resulting sObject
into JSON.serialize()
, the resulting JSON string will contain the expected key/value pair (with the composite address field itself getting serialized).
If I assign the composite address field to a variable of type System.Address
and pass that to JSON.serialize()
, or if I JSON.serialize(account.BillingAddress)
, the resulting JSON string is null.
Further, if I have an Apex class which contains a member variable of type System.Address
, JSON serialization will work as expected until I populate the System.Address
member variable.
Some code to reproduce this behavior
public class ExternalAccount{
public String name;
public Address billing_address;
public ExternalAccount(String inputName, Address inputAddress){
name = inputName;
billing_address = inputAddress;
}
}
Account acct = [SELECT Id, Name, BillingAddress FROM Account WHERE BillingStreet != null LIMIT 1][0];
ExternalAccount eaWorks = new ExternalAccount(acct.Name, null);
ExternalAccount eaFails = new ExternalAccount(acct.Name, acct.BillingAddress);
system.debug('Serializing sObject directly: ' + JSON.serialize(acct));
system.debug('Serializing BillingAddress directly: ' + JSON.serialize(acct.BillingAddress));
system.debug('Serializing Apex class, null address: ' + JSON.serialize(eaWorks));
system.debug('Serializing Apex class, populated address: ' + JSON.serialize(eaFails));
My question
Why does the JSON class completely croak on being handed System.Address
outside of an sObject
?