Newtonsoft JSON Schema Ignore Validations For Dese

2019-06-08 05:19发布

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?

2条回答
等我变得足够好
2楼-- · 2019-06-08 05:57

Another approach

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

            JavaScriptSerializer serializer=new JavaScriptSerializer();
            Student student = serializer.Deserialize<Student>(json);
查看更多
▲ chillily
3楼-- · 2019-06-08 06:01

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

enter image description here

查看更多
登录 后发表回答