この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

JSON ジェネレーター

JSONGenerator クラスのメソッドを使用して、標準 JSON で符号化されたコンテンツを生成できます。

標準 JSON 符号化方式を使用して、JSON コンテンツを要素ごとに作成できます。これを行うには、JSONGenerator クラスのメソッドを使用します。

JSONGenerator のサンプル

次の例は、JSONGenerator クラスのメソッドを使用して、見栄えのよい印刷形式の JSON 文字列を生成します。最初に数値項目と文字列項目を追加してから、整数のリストのオブジェクト項目を含める項目を追加します。この項目は適切にデシリアライズされます。次に、A オブジェクトを Object A 項目に追加します。この項目もデシリアライズされます。

1public class JSONGeneratorSample{
2
3    public 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        System.assertEquals('{\n' +
44        '  "abc" : 1.21,\n' +
45        '  "def" : "xyz",\n' +
46        '  "ghi" : {\n' +
47        '    "aaa" : [ 1, 2, 3 ]\n' +
48        '  },\n' +
49        '  "Object A" : {\n' +
50        '    "str" : "X"\n' +
51        '  }\n' +
52        '}', pretty);
53    }
54}