2012-03-19 4 views
3

.NETのRESTful Webサービス(JSONペイロード)に対してテストの自動化を行っていて、私に送信されたオブジェクトがのフィールド私が定義するDTOでは、それほど重要ではない。JSONが自分のオブジェクトに逆シリアル化しないときに例外をスローする方法

しかし、私は(System.Web.Script.Serialization)を使用しているシリアル化メソッドは、オブジェクト型が一致しない場合気にしないようです。

private class Dog 
    { 
     public string name; 
    } 
    private class Cat 
    { 
     public int legs; 
    } 
    static void Main(string[] args) 
    { 
     var dog = new Dog {name = "Fido"}; 
     var serializer = new JavaScriptSerializer(); 
     String jsonString = serializer.Serialize(dog); 
     var deserializer = new JavaScriptSerializer(); 
     Cat cat = (Cat)deserializer.Deserialize(jsonString, typeof(Cat)); 
     //No Exception Thrown! Cat has 0 legs. 
    } 

この要件をサポートする.NETシリアル化ライブラリはありますか?他のアプローチ?

答えて

3

JSONスキーマ検証を使用してこの問題を解決できます。

using System.Diagnostics; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Schema; 

public class Dog 
{ 
    public string name; 
} 

public class Cat 
{ 
    public int legs; 
} 

public class Program 
{ 
    public static void Main() 
    { 
     var dog = new Dog {name = "Fido"}; 

     // Serialize the dog 
     string serializedDog = JsonConvert.SerializeObject(dog); 

     // Infer the schemas from the .NET types 
     var schemaGenerator = new JsonSchemaGenerator(); 
     var dogSchema = schemaGenerator.Generate(typeof (Dog)); 
     var catSchema = schemaGenerator.Generate(typeof (Cat)); 

     // Deserialize the dog and run validation 
     var dogInPotentia = Newtonsoft.Json.Linq.JObject.Parse(serializedDog); 

     Debug.Assert(dogInPotentia.IsValid(dogSchema)); 
     Debug.Assert(!dogInPotentia.IsValid(catSchema)); 

     if (dogInPotentia.IsValid(dogSchema)) 
     { 
      Dog reconstitutedDog = dogInPotentia.ToObject<Dog>(); 
     } 
    } 
} 

あなたは機能hereに関する一般的な情報を見つけることができます。これを行う最も簡単な方法はそうのように、Json.NETのスキーマリフレクション機能を使用することです。

関連する問題