Newtonsoft JSON模式忽略反序列化的验证

时间:2016-09-23 12:22:58

标签: c# asp.net asp.net-mvc jsonschema

我有以下JSON&类,

{     " Id":123,     " FirstName":" fName",     "姓氏":" lName" }

public class Student
{
    public int Id { get; set; }

    [StringLength(4)]
    public string FirstName { get; set; }

    [StringLength(4)]
    public string LastName { get; set; }
} 

我试图反序列化上面的JSON来创建学生类的实例。

var body = //above json as string;

Student model = null;

JSchemaGenerator generator = new JSchemaGenerator();
JSchema schema = generator.Generate(typeof(Student));

using (JsonTextReader reader = new JsonTextReader(new StringReader(body)))
{
    using (JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader) { Schema = schema })
    {
        JsonSerializer serializer = new JsonSerializer();
        model = serializer.Deserialize(validatingReader, typeof(Student));
    }
}

这会引发字符串长度验证的异常,有没有办法通过忽略所有数据注释验证来反序列化JSON?

2 个答案:

答案 0 :(得分:3)

您可以使用以下代码反序列化数据。您在序列化之前进行验证,因为它会抛出错误。

 var body ="{\"Id\":123,\"FirstName\":\"fNamesdcsdc\",\"LastName\":\"lName\"}";
            using (JsonTextReader reader = new JsonTextReader(new StringReader(body)))
            {
                JsonSerializer serializer = new JsonSerializer();
                var model = serializer.Deserialize(reader, typeof(Student));
            }

enter image description here

答案 1 :(得分:1)

另一种方法

            String json="{ \"Id\": 123, \"FirstName\": \"fName\", \"LastName\": \"lName\" }";

            JavaScriptSerializer serializer=new JavaScriptSerializer();
            Student student = serializer.Deserialize<Student>(json);