Newer Version Available
JSON ジェネレータ
JSONGenerator クラスのメソッドを使用して、標準 JSON で符号化されたコンテンツを生成できます。
標準 JSON 符号化方式を使用して、JSON コンテンツを要素ごとに作成できます。これを行うには、JSONGenerator クラスのメソッドを使用します。
JSONGenerator のサンプル
次の例は、JSONGenerator クラスのメソッドを使用して、見栄えのよい印刷形式の JSON 文字列を生成します。最初に数値項目と文字列項目を追加してから、整数のリストのオブジェクト項目を含める項目を追加します。この項目は適切に並列化されます。次に、A オブジェクトを Object A 項目に追加します。この項目も並列化されます。
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}