Newer Version Available

This content describes an older version of this product. View Latest

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.

1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class JSONGeneratorSample{
18
19    public class A { 
20        String str;
21        
22        public A(String s) { str = s; }
23    }
24
25    static void generateJSONContent() {
26        // Create a JSONGenerator object.
27        // Pass true to the constructor for pretty print formatting.
28        JSONGenerator gen = JSON.createGenerator(true);
29        
30        // Create a list of integers to write to the JSON string.
31        List<integer> intlist = new List<integer>();
32        intlist.add(1);
33        intlist.add(2);
34        intlist.add(3);
35        
36        // Create an object to write to the JSON string.
37        A x = new A('X');
38        
39        // Write data to the JSON string.
40        gen.writeStartObject();
41        gen.writeNumberField('abc', 1.21);
42        gen.writeStringField('def', 'xyz');
43        gen.writeFieldName('ghi');
44        gen.writeStartObject();
45        
46        gen.writeObjectField('aaa', intlist);
47        
48        gen.writeEndObject();
49        
50        gen.writeFieldName('Object A');
51        
52        gen.writeObject(x);
53        
54        gen.writeEndObject();
55        
56        // Get the JSON string.
57        String pretty = gen.getAsString();
58        
59        System.assertEquals('{\n' +
60        '  "abc" : 1.21,\n' +
61        '  "def" : "xyz",\n' +
62        '  "ghi" : {\n' +
63        '    "aaa" : [ 1, 2, 3 ]\n' +
64        '  },\n' +
65        '  "Object A" : {\n' +
66        '    "str" : "X"\n' +
67        '  }\n' +
68        '}', pretty);
69    }
70}