How do I get started working with json to apex?

47    Asked by AlisonKelly in Salesforce , Asked on Sep 23, 2022

I have a specific JSON structure in mind. I need to either desterilize this structure that's coming in from a web service, or I need to serialize data into this structure to transmit it to another system. How should I get started on this project in Apex?

Answered by Amanda Hawes

Json to Apex provides multiple routes to achieving JSON serialization and deserialization of data structures. This answer summarizes use cases and capabilities of untyped deserialization, typed (de)serialization, manual implementations using JSON Generator and JSON Parser, and tools available to help support these uses. It is not intended to answer every question about JSON, but to provide an introduction, overview, and links to other resources.


Summary

Apex can serialize and desterilize JSON to strongly-typed Apex classes and also to generic collections like Map and List. In most cases, it's preferable to define Apex classes that represent data structures and utilize typed serialization and deserialization with JSON. serialize()/JSON. deserialize(). However, some use cases require applying untyped deserialization with JSON.deserialize Untyped().

The JSON Generator and JSON Parser classes are available for manual implementations and should be used only where automatic (de)serialization is not practicable, such as when keys in JSON are reserved words or invalid identifiers in Apex, or when low-level access is required.

The key documentation references are the JSON class in the Apex Developer Guide and the section JSON Support. Other relevant documentation is linked from those pages. Complex Types in Apex and JSON

JSON offers maps (or objects) and lists as its complex types. JSON lists map to Apex List objects. JSON objects can map to either Apex classes, with keys mapping to instance variables, or Apex Map objects. Apex classes and collections can be intermixed freely to construct the right data structures for any particular JSON objective.

Throughout this answer, we'll use the following JSON as an example:

{
    "errors": [ "Data failed validation rules" ],
    "message": "Please edit and retry",
    "details": {
        "record": "001000000000001",
        "record_type": "Account"
    }
}

This JSON includes two levels of nested objects, as well as a list of primitive values.

Typed Serialization  with JSON. serialize() and JSON. desterilize()

The methods JSON. serialize() and JSON .desterilize() convert between JSON and typed Apex values. When using JSON. desterilize(), you must specify the type of value you expect the JSON to yield, and Apex will attempt to desterilize that type. JSON. serialize() accepts both Apex collections and objects, in any combination that's convertible to legal JSON.

These methods are particularly useful when converting JSON to and from Apex classes, which is in most circumstances the preferred implementation pattern. The JSON example above can be represented with the following Apex class:

public class Example {
    public List errors;
    public String message;
    public class ExampleDetail {
        Id record;
        String record_type;
    }
    public ExampleDetail details;
}

To parse JSON into an Example instance, execute

Example ex = (Example)JSON. desterilize (json String, Example. class);

Alternately, to convert an Example instance into JSON, execute

String json String = JSON. serialize(ex);

Note that nested JSON objects are modelled with one Apex class per level of structure. It's not required for these classes to be inner classes, but it is a common implementation pattern. Apex only allows one level of nesting for inner classes, so deeply-nested JSON structures often convert to Apex classes with all levels of structure defined in inner classes at the top level.

JSON. serialize() and JSON. desterilize() can be used with Apex collections and classes in combination to represent complex JSON data structures. For example, JSON that stored Example instances as the values for higher-level keys:

{
    "first": { /* Example instance */ },
    "second": { /* Example instance */},
    /* ... and so on... */
}

can be serialized from, and desterilized to, a Map value in Apex.

It should be noted that this approach will not work where the JSON to be desterilized cannot be directly mapped to Apex class attributes (e.g. because the JSON property names are Apex reserved words or are invalid as Apex identifiers (e.g. contain hyphens or other invalid characters).

For more depth on typed serialization and deserialization, review the JSON class documentation. Options are available for:

Suppression of null values

Pretty-printing generated JSON

Strict deserialization, which fails on unexpected attributes

Untyped Deserialization with JSON. desterilize Untyped()

In some situations, it's most beneficial to desterilize JSON into Apex collections of primitive values, rather than into strongly-typed Apex classes. For example, this can be a valuable approach when the structure of the JSON may change in ways that aren't compatible with typed deserialization, or which would require features that Apex does not offer like algebraic or union types.

Using the JSON. desterilize Untyped() method yields an Object value, because Apex doesn't know at compile time what type of value the JSON will produce. It's necessary when using this method to typecast values pervasively.

Take, for example, this JSON, which comes in multiple variants tagged by a "scope" value:

{
    "scope": "Accounts",
    "data": {
        "payable": 100000,
        "receivable": 40000
    }
}
or
{
    "scope": {
        "division": "Sales",
        "organization": "International"
    },
    "data": {
        "closed": 400000
    }
}

JSON input that varies in this way cannot be handled with strongly-typed Apex classes because its structure is not uniform. The values for the keys scope and data have different types.

This kind of JSON structure can be desterilized using JSON. desterilize Untyped(). That method returns an Object, an untyped value whose actual type at runtime will reflect the structure of the JSON. In this case, that type would be Map, because the top level of our JSON is an object. We could desterilize this JSON via

Map result = (Map)JSON. desterilize Untyped(json String);

The untyped nature of the value we get in return cascades throughout the structure, because Apex doesn't know the type at compile time of any of the values (which may, as seen above, be heterogeneous) in this JSON object.

As a result, to access nested values, we must write defensive code that inspects values and typecasts at each level. The example above will throw a Type Exception if the resulting type is not what is expected.

To access the data for the first element in the above JSON, we might do something like this:

Object result = JSON. desterilize Untyped(json String);

if (result instance of Map) {

    Map result Map = (Map)result;

    if (result Map. get('scope') == 'Accounts' &&

        result Map. get('data') instance of Map) {

        Map data = (Map)result Map .get('data');

        if (data. get('payable') instance of Integer) {

            Integer payable = (Integer)data. get('payable');

            Accounts Service. handle Payables(payable);

        } else {

            // handle error
        }
    } else {
        // handle error
    }
} else {
    // handle error
}

While there are other ways of structuring such code, including catching JSON Exception and Type Exception, the need to be defensive is a constant. Code that fails to be defensive while working with untyped values is vulnerable to JSON changes that produce exceptions and failure modes that won't manifest in many testing practices. Common exceptions include Null Pointer Exception, when carelessly accessing nested values, and Type Exception, when casting a value to the wrong type.

Manual Implementation with JSON Generator and JSON Parser

The JSON Generator and JSON Parser classes allow your application to manually construct and parse JSON.

Using these classes entails writing explicit code to handle each element of the JSON. Using JSON Generator and JSON Parser typically yields much more complex (and much longer) code than using the built-in serialization and deserialization tools. However, it may be required in some specific applications. For example, JSON that includes Apex reserved words as keys may be handled using these classes, but cannot be desterilized to native classes because reserved words (like type and class) cannot be used as identifiers.

As a general guide, use JSON Generator and JSON Parser only when you have a specific reason for doing so. Otherwise, strive to use native serialization and deserialization, or use external tooling to generate parsing code for you (see below).

Generating Code with JSON2Apex

JSON2Apex is an open source Heroku application. JSON2Apex allows you to paste in JSON and generates corresponding Apex code to parse that JSON. The tool defaults to creating native classes for serialization  and deserialization. It automatically detects many situations where explicit parsing is required and generates JSON Parser code to desterilize JSON to native Apex objects.

JSON2Apex does not solve every problem related to using JSON, and generated code may require revision and tuning. However, it's a good place to start an implementation, particularly for users who are just getting started with JSON in Apex.

Common Workarounds

JSON attribute is a reserved word or invalid identifier

For example, you might have incoming JSON that looks like:{"currency": "USD", "unit Price" : 10.00, "_mode": "production"}

that you want to desterilize into a custom Apex Type:

public class My Stuff {

  String currency;

  Decimal unit Price;

  String _mode;

}

But currency can't be used as a variable name because it is a reserved word, nor can _mode because it is not a legal Apex identifier.

One easy workaround is to rename the variable and preprocess the JSON before desterilizing:

public class My Stuff {

  String currency X; // in JSON as currency

  Decimal unit Price;

}

  <strong>My Stuff my Stuff = (My Stuff) JSON. deserialize(the Json .replace('"currency":','"currency X":'),</strong>

                                             My Stuff.class);

However, note that this strategy can fail on large payloads. JSON2Apex is capable of generating manual deserialization code that handles invalid identifiers as well, and untyped deserialization is another option.



Your Answer