JSON Generator
Using the JSONGenerator class methods, you can generate standard JSON-encoded content.
You can construct JSON content, element by element, using the standard JSON encoding. To do so, use the methods in the JSONGenerator class.
JSONGenerator Sample
This example generates a JSON string in pretty print format by using the methods of the JSONGenerator class. The example first adds a number field and a string field, and then adds a field to contain an object field of a list of integers, which gets deserialized properly. Next, it adds the A object into the Object A field, which also gets deserialized.
1public with sharing class JSONGeneratorSample{
2
3 public with sharing class A {
4 String str;
5
6 public A(String s) { str = s; }
7 }
8
9 static void generateJSONContent() {
10 // Create a JSONGenerator object.
11 // Pass true to the constructor for pretty print formatting.
12 JSONGenerator gen = JSON.createGenerator(true);
13
14 // Create a list of integers to write to the JSON string.
15 List<integer> intlist = new List<integer>();
16 intlist.add(1);
17 intlist.add(2);
18 intlist.add(3);
19
20 // Create an object to write to the JSON string.
21 A x = new A('X');
22
23 // Write data to the JSON string.
24 gen.writeStartObject();
25 gen.writeNumberField('abc', 1.21);
26 gen.writeStringField('def', 'xyz');
27 gen.writeFieldName('ghi');
28 gen.writeStartObject();
29
30 gen.writeObjectField('aaa', intlist);
31
32 gen.writeEndObject();
33
34 gen.writeFieldName('Object A');
35
36 gen.writeObject(x);
37
38 gen.writeEndObject();
39
40 // Get the JSON string.
41 String pretty = gen.getAsString();
42
43 Assert.areEqual('''
44{
45 "abc" : 1.21,
46 "def" : "xyz",
47 "ghi" : {
48 "aaa" : [ 1, 2, 3 ]
49 },
50 "Object A" : {
51 "str" : "X"
52 }
53}''', pretty);
54 }
55}