JSON の解析
JSONParser クラスのメソッドを使用して、JSON で符号化されたコンテンツを解析できます。
JSONParser メソッドを使用して、Web サービスコールアウトの JSON 符号化方式の応答など、外部サービスへのコールから返される JSON 形式の応答を解析します。次のサンプルでは、JSON 文字列を解析する方法を示します。
サンプル: Web サービスコールアウトからの JSON 応答の解析
次の例は、JSONParser メソッドを使用して JSON 形式の応答を解析する方法を示します。この例では、JSON 形式の応答を返す Web サービスへのコールアウトを作成します。次に、応答を解析して、すべての totalPrice 項目値を取得し、価格の総計を計算します。このサンプルを実行するには、Salesforce ユーザインターフェースで Web サービスエンドポイント URL を認証済みリモートサイトとして追加する必要があります。そのためには、Salesforce にログインし、[設定] から をクリックします。
1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class JSONParserUtil {
18 @future(callout=true)
19 public static void parseJSONResponse() {
20 Http httpProtocol = new Http();
21 // Create HTTP request to send.
22 HttpRequest request = new HttpRequest();
23 // Set the endpoint URL.
24 String endpoint = 'https://docsample.herokuapp.com/jsonSample';
25 request.setEndPoint(endpoint);
26 // Set the HTTP verb to GET.
27 request.setMethod('GET');
28 // Send the HTTP request and get the response.
29 // The response is in JSON format.
30 HttpResponse response = httpProtocol.send(request);
31 System.debug(response.getBody());
32 /* The JSON response returned is the following:
33 String s = '{"invoiceList":[' +
34 '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
35 '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
36 '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
37 '"invoiceNumber":1},' +
38 '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
39 '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
40 '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
41 '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
42 ']}';
43 */
44
45 // Parse JSON response to get all the totalPrice field values.
46 JSONParser parser = JSON.createParser(response.getBody());
47 Double grandTotal = 0.0;
48 while (parser.nextToken() != null) {
49 if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
50 (parser.getText() == 'totalPrice')) {
51 // Get the value.
52 parser.nextToken();
53 // Compute the grand total price for all invoices.
54 grandTotal += parser.getDoubleValue();
55 }
56 }
57 system.debug('Grand total=' + grandTotal);
58 }
59}サンプル: JSON 文字列の解析とオブジェクトへの並列化
この例では、ハードコードされた JSON 文字列を使用します。これは、前の例のコールアウトで返された JSON 文字列と同じです。この例では、文字列全体が readValueAs メソッドを使用して Invoice オブジェクトに解析されます。また、skipChildren メソッドを使用して子配列と子オブジェクトをスキップし、リストに含まれる次の同階層の請求書を解析できるようにします。解析されたオブジェクトは、内部クラスとして定義されている Invoice クラスのインスタンスです。各請求書には品目が含まれるため、対応する品目型を表すクラスである LineItem クラスも内部クラスとして定義されます。このサンプルコードをクラスに追加して使用します。
1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static void parseJSONString() {
18 String jsonStr =
19 '{"invoiceList":[' +
20 '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
21 '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
22 '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
23 '"invoiceNumber":1},' +
24 '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
25 '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
26 '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
27 '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
28 ']}';
29
30 // Parse entire JSON response.
31 JSONParser parser = JSON.createParser(jsonStr);
32 while (parser.nextToken() != null) {
33 // Start at the array of invoices.
34 if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
35 while (parser.nextToken() != null) {
36 // Advance to the start object marker to
37 // find next invoice statement object.
38 if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
39 // Read entire invoice object, including its array of line items.
40 Invoice inv = (Invoice)parser.readValueAs(Invoice.class);
41 system.debug('Invoice number: ' + inv.invoiceNumber);
42 system.debug('Size of list items: ' + inv.lineItems.size());
43 // For debugging purposes, serialize again to verify what was parsed.
44 String s = JSON.serialize(inv);
45 system.debug('Serialized invoice: ' + s);
46
47 // Skip the child start array and start object markers.
48 parser.skipChildren();
49 }
50 }
51 }
52 }
53}
54
55// Inner classes used for serialization by readValuesAs().
56
57public class Invoice {
58 public Double totalPrice;
59 public DateTime statementDate;
60 public Long invoiceNumber;
61 List<LineItem> lineItems;
62
63 public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) {
64 totalPrice = price;
65 statementDate = dt;
66 invoiceNumber = invNumber;
67 lineItems = liList.clone();
68 }
69}
70
71public class LineItem {
72 public Double unitPrice;
73 public Double quantity;
74 public String productName;
75}