2012-03-19 88 views
3

我正在编写测试自动化在.NET中的REST风格的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模式验证来解决此问题。要做到这一点,最简单的方法是使用的Json.NET模式反射功能,像这样:

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更一般的信息。