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

Newer Version Available

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

シリアライゼーションとデシリアライゼーションの往復処理

JSON クラスのメソッドを使用して、JSON コンテンツのシリアライゼーションとデシリアライゼーションの往復処理を実行します。これらのメソッドを使用すると、オブジェクトを JSON 形式の文字列にシリアライズしたり、JSON 文字列をデシリアライズしてオブジェクトに戻したりすることができます。

例: 請求書リストのシリアライズとデシリアライズ

次の例では、InvoiceStatement オブジェクトのリストを作成して、リストをシリアライズします。次に、シリアライズされた JSON 文字列を使用してリストをデシリアライズし、元のリストに表示された請求書と同じ請求書が新しいリストに含まれることをサンプルで検証します。
1public class JSONRoundTripSample {
2  
3    public class InvoiceStatement {
4        Long invoiceNumber;
5        Datetime statementDate;
6        Decimal totalPrice;
7        
8        public InvoiceStatement(Long i, Datetime dt, Decimal price)
9        {
10            invoiceNumber = i;
11            statementDate = dt;
12            totalPrice = price;
13        }
14    }
15    
16    public static void SerializeRoundtrip() {
17        Datetime dt = Datetime.now(); 
18        // Create a few invoices.
19        InvoiceStatement inv1 = new InvoiceStatement(1,Datetime.valueOf(dt),1000);
20        InvoiceStatement inv2 = new InvoiceStatement(2,Datetime.valueOf(dt),500);
21        // Add the invoices to a list.
22        List<InvoiceStatement> invoices = new List<InvoiceStatement>();
23        invoices.add(inv1);
24        invoices.add(inv2);
25              
26        // Serialize the list of InvoiceStatement objects.
27        String JSONString = JSON.serialize(invoices);
28        System.debug('Serialized list of invoices into JSON format: ' + JSONString);
29        
30        // Deserialize the list of invoices from the JSON string.
31        List<InvoiceStatement> deserializedInvoices = 
32          (List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class);
33        System.assertEquals(invoices.size(), deserializedInvoices.size());
34        Integer i=0;
35        for (InvoiceStatement deserializedInvoice :deserializedInvoices) {
36            system.debug('Deserialized:' + deserializedInvoice.invoiceNumber + ',' 
37            + deserializedInvoice.statementDate.formatGmt('MM/dd/yyyy  HH:mm:ss.SSS')
38            + ', ' + deserializedInvoice.totalPrice); 
39            system.debug('Original:' + invoices[i].invoiceNumber + ',' 
40            + invoices[i].statementDate.formatGmt('MM/dd/yyyy  HH:mm:ss.SSS') 
41            + ', ' + invoices[i].totalPrice); 
42            i++;
43        }
44    }
45}

JSON シリアライゼーションの考慮事項

serialize メソッドの動作は、保存された Apex コードの Salesforce API バージョンによって異なります。

追加項目セットのあるクエリ対象の sObject のシリアライゼーション
Salesforce API バージョン 27.0 以前を使用して保存された Apex の場合、クエリ対象の sObject に追加項目セットがある場合、これらの項目は serialize メソッドによって返されるシリアライズされた JSON 文字列に含まれません。Salesforce API バージョン 28.0 以降を使用して保存された Apex で開始する場合は、シリアライズされる JSON 文字列に追加項目が含まれます。
次の例では、照会された後に項目が取引先責任者に追加され、その後取引先責任者がシリアライズされます。アサーションステートメントは、JSON 文字列に追加項目が含まれていることを検証します。このアサーションは、Salesforce API バージョン 28.0 以降を使用して保存された Apex に対して有効です。
1Contact con = [SELECT Id, LastName, AccountId FROM Contact LIMIT 1]
2// Set additional field
3con.FirstName = 'Joe'
4String jsonstring = Json.serialize(con)
5System.debug(jsonstring)
6System.assert(jsonstring.contains('Joe') == true);
集計クエリの結果項目のシリアライゼーション
Salesforce API バージョン 27.0 を使用して保存された Apex の場合、serialize メソッドを使用してシリアライズすると、集計クエリの結果に SELECT ステートメントの項目は含まれません。API の以前のバージョン、または API バージョン 28.0 以降の場合、シリアライズされた集計クエリの結果に SELECT ステートメントのすべての項目が含まれます。
この集計クエリは、2 つの項目 (ID 項目の数と取引先名) を返します。
1String jsonString = JSON.serialize(
2    Database.query('SELECT Count(Id),Account.Name FROM Contact WHERE Account.Name != null GROUP BY Account.Name LIMIT 1'));
3    System.debug(jsonString);
4
5// Expected output in API v 26 and earlier or v28 and later
6// [{"attributes":{"type":"AggregateResult"},"expr0":2,"Name":"acct1"}]
空の項目のシリアライゼーション
API バージョン 28.0 以降はそれまでのバージョンとは異なり、null 項目はシリアライズされず、JSON 文字列には含まれません。この変更は、Json.deserialize() などの JSON メソッドを使用した JSON 文字列のデシリアライズには影響しません。JSON 文字列を調べるときにこの変更の影響が顕著に現れます。次に例を示します。
1String jsonString = JSON.serialize(
2                 [SELECT Id, Name, Website FROM Account WHERE Website = null LIMIT 1]);
3System.debug(jsonString);
4
5// In v27.0 and earlier, the string includes the null field and looks like the following.
6// {"attributes":{...},"Id":"001D000000Jsm0WIAR","Name":"Acme","Website":null}
7
8// In v28.0 and later, the string doesn’t include the null field and looks like 
9//  the following.
10// {"attributes":{...},"Name":"Acme","Id":"001D000000Jsm0WIAR"}}
ID のシリアライゼーション
API バージョン 34.0 以前では、JSON のシリアライゼーションとデシリアライゼーションの往復処理後の ID に対する == を使用した ID の比較は失敗します。