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

Newer Version Available

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

JSON の解析

JSONParser クラスのメソッドを使用して、JSON で符号化されたコンテンツを解析します。これらのメソッドを使用して、Web サービスコールアウトなど、外部サービスへのコールから返される JSON 形式の応答を解析できます。

次のサンプルでは、JSON 文字列を解析する方法を示します。

例: Web サービスコールアウトからの JSON 応答の解析

次の例では、JSONParser メソッドを使用して JSON 形式の応答を解析します。JSON 形式の応答を返す Web サービスへのコールアウトを行います。次に、応答が解析され、API バージョン番号からリリース表示ラベルへの対応付けが作成されます。

1public class JSONParserUtil {
2    public static void parseJSONResponse() {        
3        
4        // Create HTTP request to send.
5        HttpRequest request = new HttpRequest();
6        // Set the endpoint URL.
7        String endpoint = URL.getOrgDomainUrl().toExternalForm() + '/services/data';
8        request.setEndPoint(endpoint);
9        // Set the HTTP verb to GET.
10        request.setMethod('GET');
11        // Set the request header for JSON content type
12        request.setHeader('Accept', 'application/json');
13        
14        // Send the HTTP request and get the response.
15        // The response is in JSON format.
16        Http httpProtocol = new Http();
17        HttpResponse response = httpProtocol.send(request);
18        System.debug(response.getBody());
19        /* The JSON response returned is the following:
20            {"label":"Summer '14","url":"/services/data/v31.0","version":"31.0"},
21            {"label":"Winter '15","url":"/services/data/v32.0","version":"32.0"},
22            {"label":"Spring '15","url":"/services/data/v33.0","version":"33.0"},
23        */
24        // Parse JSON response to build a map from API version numbers to labels
25        JSONParser parser = JSON.createParser(response.getBody());
26        Map<double, string> apiVersionToReleaseNameMap = new Map<double, string>();
27        
28        string label = null;
29        double version = null;
30        
31        while (parser.nextToken() != null) {
32            
33            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
34                switch on parser.getText() {
35                    when 'label' {
36                    // Advance to the label value.
37                    parser.nextToken();
38                        label = parser.getText();
39                    }
40                    when 'version' {
41                        // Advance to the version value.
42                        parser.nextToken();
43                        version = Double.valueOf(parser.getText());
44                    }
45                }
46            }
47            
48            if(version != null && String.isNotEmpty(label)) {
49                apiVersionToReleaseNameMap.put(version, label);
50                version = null;
51                label = null; 
52            }
53        }
54        system.debug('Release with Rainbow logo = ' +
55            apiVersionToReleaseNameMap.get(39.0D));
56    }
57}

例: 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}