Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apex Address compound type, based on that provided in Spring'14 for Salesforce API, http://www.salesforce.com/us/developer/docs/api/Content/compound_fields_address.htm
public class Address
{
// Internally used to determine if valueOf method should read the state and country picker fields
private static Boolean stateAndCountryPickersEnabled = false;
static
{
// Are State and Country pickers enabled in this org?
Map<String, Schema.SObjectField> accountFields = Account.sObjectType.getDescribe().fields.getMap();
stateAndCountryPickersEnabled = accountFields.containsKey('BillingStateCode');
}
public String City;
public String Country;
public String CountryCode;
public String State;
public String StateCode;
public String Street;
public String PostalCode;
/**
* Fields on the Account object that contain address information
**/
public enum AccountAddress
{
Billing,
Shipping
}
/**
* Fields on the Contact object that contain address information
**/
public enum ContactAddress
{
Mailing,
Other
}
/**
* Extract address information for the given fields from an Account
**/
public static Address valueOf(Account account, AccountAddress address)
{
return valueOf(account, address.name());
}
/**
* Extract address information for the given fields from a Contact
**/
public static Address valueOf(Contact contact, ContactAddress address)
{
return valueOf(contact, address.name());
}
/**
* Constructs an Address instance from a given SObject
**/
private static Address valueOf(SObject sObj, String fieldPrefix)
{
Address address = new Address();
address.City = (String) sObj.get(fieldPrefix+'City');
address.Country = (String) sObj.get(fieldPrefix+'Country');
address.State = (String) sObj.get(fieldPrefix+'State');
address.Street = (String) sObj.get(fieldPrefix+'Street');
address.PostalCode = (String) sObj.get(fieldPrefix+'PostalCode');
if(stateAndCountryPickersEnabled)
{
address.CountryCode = (String) sObj.get(fieldPrefix+'CountryCode');
address.StateCode = (String) sObj.get(fieldPrefix+'StateCode');
}
return address;
}
}
public with sharing class AddressJSON {
public static void demo()
{
// Query Account and approprite fields
Account myAccount =
[select Id,
BillingCity,
BillingCountry,
BillingCountryCode,
BillingPostalCode,
BillingState,
BillingStateCode,
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment