WinRT APIでJSONフォーマットをデシリアライズする方法

前に投稿した、WinRT APIでJSONフォーマットをでシリアライズする方法 の続編です。

 

シリアライズしたいJSONのフォーマットが、

{"__type":"UserTypeA:#UserTypeNS","Properties":{"PropertyX":"ValueX", "PropertyY":"ValueY"},"DataPackets":[{"__type":"UserTypeB:#UserTypeNS","PropertyA":"ValueA","PropertyB":"ValueB"}],"Values":["1","2","5"]}

といったような形式をとる場合のデシリアライズロジックを紹介します。

先ず、JSONのデータを表現するクラスを定義します。

namespace UserTypeNS
{

    [DataContract]
    public class UserTypeA
    {
        [DataMember]
        public List<UserTypeB> DataPacketA;
        [DataMember]
        public List<int> Values;
    }

    [DataContract]
    public class UserTypeB
    {
        [DataMember]
        public string PropertyA;
        [DataMember]
        public string PropertyB;
    }

    [DataContract]
    public class PropertiesType
    {
        [DataMember]
        public string PropertyX;
        [DataMember]
        public string PropertyY;
    }
}

JSONの中の、"__type":"XXX:#NS"の項目は、何らかの標準で規定されたデータ型であり、その情報なので、データクラスの中でプロパティで定義する必要はありません。
デシリアライズするコードは、

    List<Type> types = new List<Type>();
    types.Add(typeof(UserTypeNS.UserTypeA));
    types.Add(typeof(UserTypeNS.UserTypeB));
    types.Add(typeof(UserTypeNS.PropertiesType));

    var dcjs = new DataContractJsonSerializer(typeof(UserTypeNS.UserTypeA), types);
            
    var data= dcjs.ReadObject(stream) as UserTypeNS.UserTypeA;

となります。デシリアライザーを作成するときに、デシリアライザーに対して型の定義を教えてあげるために、JSONの中で使われている方を、リストかして教えるわけです。

以上です。簡単ですね~。