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

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

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

WeaklyTypedJson サンプルでは、WCF 開発者がユーザー定義型を作成せずに、逆シリアル化された任意の JSON オブジェクトを使用できるメカニズムを提供します。 このしくみは、JSON オブジェクトが逆シリアル化される型がコンパイル時に不明なため、JSON オブジェクトの 弱い型指定のシリアル化 と呼ばれます。

たとえば、パブリック 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"] オブジェクトの詳細については、「 Mapping Between JSON and XML」トピックで説明されているように、JavaScript Object Notation (JSON) オブジェクトを使用する場合にも適用されます。

Note

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

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

Service listening at http://localhost:8000/.
To view the JSON output from the sample, navigate to http://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. Building the Windows Communication Foundation Samples」の説明に従って、ソリューション WeaklyTypedJson.sln をビルドします。

  3. ソリューションを実行する