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