Thursday, August 5, 2021

Working with JSON in Apex

We can serialize and deserialize JSON to strongly-typed Apex classes and also to generic collections like Map<String, Object> and List<Object> in Apex.

Different way to use JSON in Apex.

  •  Typed serialization and deserialization with JSON.serialize()/JSON.deserialize(). 
  •  Untyped deserialization with JSON.deserializeUntyped().

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

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

The methods JSON.serialize() and JSON.deserialize() convert between JSON and typed Apex values.

 When using JSON.deserialize(), you must specify the type of value you expect the JSON to yield, and Apex will attempt to deserialize to that type.

 JSON.serialize() accepts both Apex collections and objects, in any combination that’s convertible to legal JSON.

JSON as an example:

{

"errors": [ "Request failed validation rules" ],

"message": "Please provide data and retry",

"details": {

"record": "001000000000091",

"record_type": "Account"

}

}

Apex class:

public class Example {

public List<String> 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.deserialize(jsonString, Example.class);

Alternately, to convert an Example instance into JSON, execute

String jsonString = JSON.serialize(ex);


Untyped Deserialization with JSON.deserializeUntyped()


Using the JSON.deserializeUntyped() method yields an Object value, because Apex doesn’t know at compile time what type of value the JSON will produce

Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(jsonString);