Newer Version Available
Roundtrip Serialization and Deserialization
Use the JSON class methods to perform roundtrip
serialization and deserialization of your JSON content. These methods enable you to
serialize objects into JSON-formatted strings and to deserialize JSON strings back into
objects.
Example: Serialize and Deserialize a List of Invoices
This example creates a list of InvoiceStatement objects and serializes the list. Next, the serialized
JSON string is used to deserialize the list again and the sample verifies that the
new list contains the same invoices that were present in the original
list.
1public class JSONRoundTripSample {
2
3 public class InvoiceStatement {
4 Long invoiceNumber;
5 Datetime statementDate;
6 Decimal totalPrice;
7
8 public InvoiceStatement(Long i, Datetime dt, Decimal price)
9 {
10 invoiceNumber = i;
11 statementDate = dt;
12 totalPrice = price;
13 }
14 }
15
16 public static void SerializeRoundtrip() {
17 Datetime dt = Datetime.now();
18 // Create a few invoices.
19 InvoiceStatement inv1 = new InvoiceStatement(1,Datetime.valueOf(dt),1000);
20 InvoiceStatement inv2 = new InvoiceStatement(2,Datetime.valueOf(dt),500);
21 // Add the invoices to a list.
22 List<InvoiceStatement> invoices = new List<InvoiceStatement>();
23 invoices.add(inv1);
24 invoices.add(inv2);
25
26 // Serialize the list of InvoiceStatement objects.
27 String JSONString = JSON.serialize(invoices);
28 System.debug('Serialized list of invoices into JSON format: ' + JSONString);
29
30 // Deserialize the list of invoices from the JSON string.
31 List<InvoiceStatement> deserializedInvoices =
32 (List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class);
33 System.assertEquals(invoices.size(), deserializedInvoices.size());
34 Integer i=0;
35 for (InvoiceStatement deserializedInvoice :deserializedInvoices) {
36 system.debug('Deserialized:' + deserializedInvoice.invoiceNumber + ','
37 + deserializedInvoice.statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS')
38 + ', ' + deserializedInvoice.totalPrice);
39 system.debug('Original:' + invoices[i].invoiceNumber + ','
40 + invoices[i].statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS')
41 + ', ' + invoices[i].totalPrice);
42 i++;
43 }
44 }
45}JSON Serialization Considerations
The behavior of the serialize method differs depending on the Salesforce API version of the Apex code saved.
- Serialization of queried sObject with additional fields set
- For Apex saved using Salesforce API version 27.0 and earlier, if queried sObjects have additional fields set, these fields aren’t included in the serialized JSON string returned by the serialize method. Starting with Apex saved using Salesforce API version 28.0, the additional fields are included in the serialized JSON string.
- This example adds a field to a contact after it has been queried, and then
serializes the contact. The assertion statement verifies that the JSON
string contains the additional field. The assertion passes for Apex saved
using Salesforce API version 28.0 and
later.
1Contact con = [SELECT Id, LastName, AccountId FROM Contact LIMIT 1]; 2// Set additional field 3con.FirstName = 'Joe'; 4String jsonstring = Json.serialize(con); 5System.debug(jsonstring); 6System.assert(jsonstring.contains('Joe') == true); - Serialization of aggregate query result fields
- For Apex saved using Salesforce API version 27.0, results of aggregate queries don’t include the fields in the SELECT statement when serialized using the serialize method. For earlier API versions or for API version 28.0 and later, serialized aggregate query results include all fields in the SELECT statement.
- This aggregate query returns two fields: the count of ID fields and the
account name.
1String jsonString = JSON.serialize( 2 Database.query('SELECT Count(Id),Account.Name FROM Contact WHERE Account.Name != null GROUP BY Account.Name LIMIT 1')); 3 System.debug(jsonString); 4 5// Expected output in API v 26 and earlier or v28 and later 6// [{"attributes":{"type":"AggregateResult"},"expr0":2,"Name":"acct1"}] - Serialization of empty fields
- Starting with API version 28.0, null fields aren’t serialized and aren’t
included in the JSON string, unlike in earlier versions. This change doesn’t
affect deserializing JSON strings with JSON methods, such as deserialize(jsonString, apexType). This change is noticeable when you
inspect the JSON string. For
example:
1String jsonString = JSON.serialize( 2 [SELECT Id, Name, Website FROM Account WHERE Website = null LIMIT 1]); 3System.debug(jsonString); 4 5// In v27.0 and earlier, the string includes the null field and looks like the following. 6// {"attributes":{...},"Id":"001D000000Jsm0WIAR","Name":"Acme","Website":null} 7 8// In v28.0 and later, the string doesn’t include the null field and looks like 9// the following. 10// {"attributes":{...},"Name":"Acme","Id":"001D000000Jsm0WIAR"}} - Serialization of IDs
- In API version 34.0 and earlier, ID comparison using == fails for IDs that have been through roundtrip JSON serialization and deserialization.