Newtonsoft JSON Schema Ignore Validations For Deserialize

倖福魔咒の 提交于 2019-12-23 02:47:18

问题


I have following JSON & class,

{ "Id": 123, "FirstName": "fName", "LastName": "lName" }

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

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

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

I'm trying to deserialize above JSON to create an instance of student class.

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));
    }
}

This is throwing an exception for string length validation, is there any way to deserialize the JSON by ignoring all data annotation validations?


回答1:


You can deserialize your data using the below code. You are validating before serializing due to which it is throwing error.

 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));
            }




回答2:


Another approach

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

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


来源:https://stackoverflow.com/questions/39660684/newtonsoft-json-schema-ignore-validations-for-deserialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!