Apex Method of the Day – JSON.serialize(Object)

Sometimes using JSON.serialize on a custom Apex type does not provide sufficient control over how the JSON is serialized. For example, serializing an Apex type will include null values for all fields that haven’t been set, when you might prefer to omit these properties from the JSON altogether. Or perhaps you need to use a property name in the JSON which is invalid for a class member name Apex. Fortunately JSON.serialize works on any Object, so you can serialize JSON from any structure you can assemble in Apex, for example:

String jsonString = JSON.serialize(new Map<String,Object> {
	'datetimevalue' => System.now(),
	'somelist' => new List<Object> {
		new Map<String,Object> {
			'name' => 'Mac',
			'os' => 'OS X 10.9'
		},
		new Map<String,Object> {
			'name' => 'PC',
			'os' => 'Windows'
		}
	}
});

JSON:

{
    "somelist": [
        {
            "name": "Mac",
            "os": "OS X 10.9"
        },
        {
            "name": "PC",
            "os": "Windows"
        }
    ],
    "datetimevalue": "2014-07-25T10:47:34.981Z"
}

Links:
Salesforce Stackexchange Question
JSON class

This entry was posted in Documentation and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s