I want to serialize just the Address object (lets call it an object) of Account (and Contact as well)
Is there a way to access the ShippingAddress/BillingAddress of the account using the JSON.serialize method?
Address information is surfaced in two ways on these objects...
Standard addresses—addresses built into standard objects in Salesforce—are accessible in the SOAP and REST APIs as an Address, a structured compound data type, as well as individual address elements.
// Query Account and approprite fields
Account myAccount =
[select Id,
BillingCity,
BillingCountry,
BillingPostalCode,
BillingState,
BillingStreet
from Account
where Name = 'Burlington Textiles Corp of America' limit 1];
// Create a Billing Address
Address billingAddress =
Address.valueOf(myAccount, Address.AccountAddress.Billing);
// Serialise it via JSON
String jsonBillingAddress = JSON.serialize(billingAddress);
System.debug(jsonBillingAddress);
This outputs...
11:35:55.344 (344137285)|USER_DEBUG|[22]|DEBUG|{"Street":"525 S. Lexington Ave","StateCode":null,"State":"NC","PostalCode":"27215","CountryCode":null,"Country":"USA","City":"Burlington"}
NOTE: The Address type also supports the State and Country pick list feature if enabled in the org.