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" }