问题
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