Reference Apex Standard Classes and Methods
Method Arguments Return Type Description
' "type" : null,\n' +
' "inventory" : 2000,\n' +
' "price" : 1023.45,\n' +
' "isShipped" : true,\n' +
' "modelNumber" : "123"\n' +
'}';
Map<String, Object> m =
(Map<String, Object>)
JSON.deserializeUntyped(jsonInput);
System.assertEquals(
'An appliance', m.get('description'));
List<Object> a =
(List<Object>)m.get('accessories');
System.assertEquals('powerCord', a[0]);
Map<String, Object> a2 =
(Map<String, Object>)a[1];
System.assertEquals(
'door handle1', a2.get('right'));
System.assertEquals(
'door handle2', a2.get('left'));
Map<String, Object> dim =
(Map<String, Object>)m.get('dimensions');
System.assertEquals(
5.5, dim.get('height'));
System.assertEquals(
3.0, dim.get('width'));
System.assertEquals(
2.2, dim.get('depth'));
System.assertEquals(null, m.get('type'));
System.assertEquals(
2000, m.get('inventory'));
System.assertEquals(
1023.45, m.get('price'));
System.assertEquals(
true, m.get('isShipped'));
System.assertEquals(
'123', m.get('modelNumber'));
serialize Any type String Serializes Apex objects into JSON content.
object
The object argument is the Apex object to serialize.
The following example serializes a new Datetime value.
Datetime dt = Datetime.newInstance(
Date.newInstance(
2011, 3, 22),
Time.newInstance(
1, 15, 18, 0));
String str = JSON.serialize(dt);
System.assertEquals(
'"2011-03-22T08:15:18.000Z"',
str);
437
Reference Apex Standard Classes and Methods
Method Arguments Return Type Description
serializePretty Any type String Serializes Apex objects into JSON content and generates
object indented content using the pretty-print format.
The object argument is the Apex object to serialize.
Sample: Serializing and Deserializing a List of Invoices
This sample 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.
public class JSONRoundTripSample {
public class InvoiceStatement {
Long invoiceNumber;
Datetime statementDate;
Decimal totalPrice;
public InvoiceStatement(Long i, Datetime dt, Decimal price)
{
invoiceNumber = i;
statementDate = dt;
totalPrice = price;
}
}
public static void SerializeRoundtrip() {
Datetime dt = Datetime.now();
// Create a few invoices.
InvoiceStatement inv1 = new InvoiceStatement(1,Datetime.valueOf(dt),1000);
InvoiceStatement inv2 = new InvoiceStatement(2,Datetime.valueOf(dt),500);
// Add the invoices to a list.
List<InvoiceStatement> invoices = new List<InvoiceStatement>();
invoices.add(inv1);
invoices.add(inv2);
// Serialize the list of InvoiceStatement objects.
String JSONString = JSON.serialize(invoices);
System.debug('Serialized list of invoices into JSON format: ' + JSONString);
// Deserialize the list of invoices from the JSON string.
List<InvoiceStatement> deserializedInvoices =
(List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class);
System.assertEquals(invoices.size(), deserializedInvoices.size());
Integer i=0;
for (InvoiceStatement deserializedInvoice :deserializedInvoices) {
system.debug('Deserialized:' + deserializedInvoice.invoiceNumber + ','
+ deserializedInvoice.statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS')
+ ', ' + deserializedInvoice.totalPrice);
system.debug('Original:' + invoices[i].invoiceNumber + ','
+ invoices[i].statementDate.formatGmt('MM/dd/yyyy HH:mm:ss.SSS')
+ ', ' + invoices[i].totalPrice);
i++;
}
}
}
438
Reference Apex Standard Classes and Methods
JSON Serialization Considerations
The following describes differences in behavior for the serialize method. Those differences depend on the Salesforce.com
API version of the Apex code saved.
Serialization of queried sObject with additional fields set
For Apex saved using Salesforce.com 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.com 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. This assertion passes for Apex saved using Salesforce.com
API version 28.0 and later.
Contact con = [SELECT Id, LastName, AccountId FROM Contact LIMIT 1];
// Set additional field
con.FirstName = 'Joe';
String jsonstring = Json.serialize(con);
System.debug(jsonstring);
System.assert(jsonstring.contains('Joe') == true);
Serialization of aggregate query result fields
For Apex saved using Salesforce.com 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 is an example of an aggregate query that returns two fields, the count of ID fields and the account name.
String jsonString = JSON.serialize(
Database.query('SELECT Count(Id),Account.Name FROM Contact WHERE Account.Name !=
null GROUP BY Account.Name LIMIT 1'));
System.debug(jsonString);
// Expected output in API v 26 and earlier or v28 and later
// [{"attributes":{"type":"AggregateResult"},"expr0":2,"Name":"acct1"}]
See Also:
Type Methods
JSONGenerator Methods
Contains methods used to serialize Apex objects into JSON content using the standard JSON encoding.
Usage
Since the JSON encoding that's generated by Apex through the serialization method in the System.JSON class isn't identical
to the standard JSON encoding in some cases, the System.JSONGenerator class is provided to enable the generation of
standard JSON-encoded content.
Methods
The following are instance methods of the System.JSONGenerator class.
439
Reference Apex Standard Classes and Methods
Method Arguments Return Type Description
close Void Closes the JSON generator.
No more content can be written after the JSON generator is
closed.
getAsString String Returns the generated JSON content.
Also, this method closes the JSON generator if it isn't closed
already.
isClosed Boolean Returns true if the JSON generator is closed; otherwise,
returns false.
writeBlob Blob blobValue Void Writes the specified Blob value as a base64-encoded string.
writeBlobField String fieldName Void Writes a field name and value pair using the specified field
name and BLOB value.
Blob blobValue
writeBoolean Boolean Void Writes the specified Boolean value.
blobValue
writeBooleanField String fieldName Void Writes a field name and value pair using the specified field
name and Boolean value.
Boolean
booleanValue
writeDate Date dateValue Void Writes the specified date value in the ISO-8601 format.
writeDateField String fieldName Void Writes a field name and value pair using the specified field
name and date value. The date value is written in the
Date dateValue
ISO-8601 format.
writeDateTime Datetime Void Writes the specified date and time value in the ISO-8601
datetimeValue format.
writeDateTimeField String fieldName Void Writes a field name and value pair using the specified field
name and date and time value. The date and time value is
Datetime
written in the ISO-8601 format.
datetimeValue
writeEndArray Void Writes the ending marker of a JSON array (']').
writeEndObject Void Writes the ending marker of a JSON object ('}').
writeFieldName String fieldName Void Writes a field name.
writeId ID identifier Void Writes the specified ID value.
writeIdField String fieldName Void Writes a field name and value pair using the specified field
name and identifier value.
Id identifier
writeNull Void Writes the JSON null literal value.
writeNullField String fieldName Void Writes a field name and value pair using the specified field
name and the JSON null literal value.
writeNumber Decimal number Void Writes the specified decimal value.
writeNumber Double number Void Writes the specified double value.
440
Reference Apex Standard Classes and Methods
Method Arguments Return Type Description
writeNumber Integer number Void Writes the specified integer value.
writeNumber Long number Void Writes the specified long value.
writeNumberField String fieldName Void Writes a field name and value pair using the specified field
name and decimal value.
Decimal number
writeNumberField String fieldName Void Writes a field name and value pair using the specified field
name and double value.
Double number
writeNumberField String fieldName Void Writes a field name and value pair using the specified field
name and integer value.
Integer number
writeNumberField String fieldName Void Writes a field name and value pair using the specified field
name and long value.
Long number
writeObject Any type object Void Writes the specified Apex object in JSON format
writeObjectField String fieldName Void Writes a field name and value pair using the specified field
name and Apex object.
Any type object
writeStartArray Void Writes the starting marker of a JSON array ('[').
writeStartObject Void Writes the starting marker of a JSON object ('{').
writeString String Void Writes the specified string value.
stringValue
writeStringField String fieldName Void Writes a field name and value pair using the specified field
name and string value.
String
stringValue
writeTime Time timeValue Void Writes the specified time value in the ISO-8601 format.
writeTimeField String fieldName Void Writes a field name and value pair using the specified field
name and time value in the ISO-8601 format.
Time timeValue
JSONGenerator Sample
This example generates a JSON string by using the methods of JSONGenerator.
public class JSONGeneratorSample{
public class A {
String str;
public A(String s) { str = s; }
}
static void generateJSONContent() {
// Create a JSONGenerator object.
// Pass true to the constructor for pretty print formatting.
JSONGenerator gen = JSON.createGenerator(true);
441