弱い型指定の JSON のシリアル化のサンプル

特定のワイヤ形式にユーザー定義型をシリアル化するときや、ユーザー定義型にワイヤ形式を逆シリアル化するときは、そのユーザー定義型がサービスとクライアントの両方で使用可能である必要があります。通常、これを実現するために、DataContractAttribute 属性がこのユーザー定義型に適用され、DataMemberAttribute 属性がそのメンバに適用されます。この機構は、「方法 : JSON データをシリアル化および逆シリアル化する」トピックで説明されているように、JavaScript Object Notation (JSON) オブジェクトを使用する場合にも適用されます。

場合によっては、Windows Communication Foundation (WCF) サービスまたはクライアントが、開発者の管理外にあるサービスまたはクライアントによって生成された JSON オブジェクトにアクセスする必要があります。より多くの Web サービスによって JSON API がパブリックとして公開されると、WCF 開発者がローカルのユーザー定義型を構築し、任意の JSON オブジェクトを逆シリアル化することが実用的でなくなる可能性があります。このサンプルでは、WCF 開発者がユーザー定義型を作成せずに、逆シリアル化された任意の JSON オブジェクトを使用できる機構を示します。このしくみは、JSON オブジェクトが逆シリアル化される型がコンパイル時に不明なため、JSON オブジェクトの弱い型指定のシリアル化と呼ばれます。

Bb943471.note(ja-jp,VS.100).gif注 :
このサンプルのセットアップ手順とビルド手順については、このトピックの最後を参照してください。

たとえば、パブリック Web サービスの API によって、このサービスのユーザーに関する情報の一部を記述した次の JSON オブジェクトが返されるとします。

{"personal": {"name": "Paul", "age": 23, "height": 1.7, "isSingle": true, "luckyNumbers": [5,17,21]}, "favoriteBands": ["Band ABC", "Band XYZ"]}

このオブジェクトを逆シリアル化するために、WCF クライアントは次のユーザー定義型を実装する必要があります。

   [DataContract]
    public class MemberProfile
    {
        [DataMember]
        public PersonalInfo personal;

        [DataMember]
        public string[] favoriteBands;
    }

    [DataContract]
    public class PersonalInfo
    {
        [DataMember]
        public string name;

        [DataMember]
        public int age;

        [DataMember]
        public double height;

        [DataMember]
        public bool isSingle;

        [DataMember]
        public int[] luckyNumbers;
    }

この手順は、特にクライアントが複数の型の JSON オブジェクトを処理する必要がある場合に、複雑になる可能性があります。

このサンプルで示す JsonObject 型では、逆シリアル化された JSON オブジェクトの弱い型指定の表現を使用します。JsonObject は、JSON オブジェクトと .NET Framework ディクショナリ間の自然な割り当て、および JSON 配列と .NET Framework 配列間の割り当てに依存しています。JsonObject 型のコードを次に示します。

// Instantiation of JsonObject json omitted

string name = json["root"]["personal"]["name"];
int age = json["root"]["personal"]["age"];
double height = json["root"]["personal"]["height"];
bool isSingle = json["root"]["personal"]["isSingle"];
int[] luckyNumbers = {
                                     json["root"]["personal"]["luckyNumbers"][0],
                                     json["root"]["personal"]["luckyNumbers"][1],
                                     json["root"]["personal"]["luckyNumbers"][2] 
                                 };
string[] favoriteBands = {
                                        json["root"]["favoriteBands"][0],
                                        json["root"]["favoriteBands"][1]
                                    };

コンパイル時に型を宣言せずに、JSON オブジェクトと配列を "参照" できます。トップレベルの ["root"] オブジェクトの詳細については、「JSON と XML 間のマッピング」を参照してください。

Bb943471.note(ja-jp,VS.100).gif注 :
JsonObject クラスは、例としてのみ提供されています。テストが完全には行われていないため、運用環境では使用しないでください。弱い型指定の JSON のシリアル化の明確な影響の 1 つは、JsonObject の使用時にタイプ セーフがなくなることです。

JsonObject 型を使用するには、クライアント操作コントラクトで Message を戻り値の型として使用する必要があります。

[ServiceContract]
    interface IClientSideProfileService
    {
        // There is no need to write a DataContract for the complex type returned by the service.
        // The client will use a JsonObject to browse the JSON in the received message.

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        Message GetMemberProfile();
    }

次のコードに示すように、JsonObject がインスタンス化されます。

// Code to instantiate IClientSideProfileService channel omitted…

// Make a request to the service and obtain the Json response
XmlDictionaryReader reader = channel.GetMemberProfile().GetReaderAtBodyContents();

// Go through the Json as though it is a dictionary. There is no need to map it to a .NET CLR type.
JsonObject json = new JsonObject(reader);

JsonObject コンストラクタは、GetReaderAtBodyContents メソッドを使用して取得される XmlDictionaryReader を受け取ります。リーダーには、クライアントによって受信された JSON メッセージの XML 表現が含まれています。詳細については、次のトピックを参照してください。「JSON と XML 間のマッピング」を参照してください。

このプログラムの出力は、次のようになります。

Service listening at https://localhost:8000/.
To view the JSON output from the sample, navigate to https://localhost:8000/GetMemberProfile
This is Paul's page. I am 23 years old and I am 1.7 meters tall.
I am single.
My lucky numbers are 5, 17, and 21.
My favorite bands are Band ABC and Band XYZ.

サンプルを設定、ビルド、および実行するには

  1. Windows Communication Foundation サンプルの 1 回限りのセットアップの手順」が実行済みであることを確認します。

  2. Windows Communication Foundation サンプルのビルド」の説明に従って、ソリューション WeaklyTypedJson.sln をビルドします。

  3. ソリューションを実行します。

Bb943471.Important(ja-jp,VS.100).gif 注 :
サンプルは、既にコンピューターにインストールされている場合があります。続行する前に、次の (既定の) ディレクトリを確認してください。

<InstallDrive>:\WF_WCF_Samples

このディレクトリが存在しない場合は、「.NET Framework 4 向けの Windows Communication Foundation (WCF) および Windows Workflow Foundation (WF) のサンプル」にアクセスして、Windows Communication Foundation (WCF) および WF のサンプルをすべてダウンロードしてください。このサンプルは、次のディレクトリに格納されます。

<InstallDrive>:\WF_WCF_Samples\WCF\Scenario\Ajax\WeaklyTypedJson