Vijay Chauhan Vijay Chauhan - 2 months ago 28
ASP.NET (C#) Question

Newtonsoft JSON Schema Ignore Validations For Deserialize

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?

Answer

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