JSON Support

JavaScript Object Notation (JSON) support in Apex enables the serialization of Apex objects into JSON format and the deserialization of serialized JSON content.
Apex provides a set of classes that expose methods for JSON serialization and deserialization. The following table describes the classes available.
Class Description
System.JSON Contains methods for serializing Apex objects into JSON format and deserializing JSON content that was serialized using the serialize method in this class.
System.JSONGenerator Contains methods used to serialize objects into JSON content using the standard JSON encoding.
System.JSONParser Represents a parser for JSON-encoded content.

The System.JSONToken enumeration contains the tokens used for JSON parsing.

Methods in these classes throw a JSONException if an issue is encountered during execution.

JSON Support Considerations
  • JSON serialization and deserialization support is available for sObjects (standard objects and custom objects), Apex primitive and collection types, return types of Database methods (such as SaveResult, DeleteResult, and so on), and instances of your Apex classes.
  • Only custom objects, which are sObject types, of managed packages can be serialized from code that is external to the managed package. Objects that are instances of Apex classes defined in the managed package can't be serialized.
  • A Map object is serializable into JSON only if it uses one of the following data types as a key.
  • When an object is declared as the parent type but is set to an instance of the subtype, some data may be lost. The object gets serialized and deserialized as the parent type and any fields that are specific to the subtype are lost.
  • An object that has a reference to itself won’t get serialized and causes a JSONException to be thrown.
  • Reference graphs that reference the same object twice are deserialized and cause multiple copies of the referenced object to be generated.
  • The System.JSONParser data type isn’t serializable. If you have a serializable class, such as a Visualforce controller, that has a member variable of type System.JSONParser and you attempt to create this object, you’ll receive an exception. To use JSONParser in a serializable class, use a local variable instead in your method.
Previous
Next