0

Is it possible to make JsonConvert.Deserialize<T>() throw an exception whenever the incoming JSON does not FULLY match specified type's properties' names/types?

It just fills props with default values.

tokechu
  • 150
  • 1
  • 14
  • 1
    you can use JSON Schema to validate incoming json and throw exception if it is not matching . https://www.newtonsoft.com/json/help/html/JsonSchema.htm – Deepak Koshy Mar 28 '22 at 11:27
  • For missing/extra properties, do [Detect if deserialized object is missing a field with the JsonConvert class in Json.NET](https://stackoverflow.com/q/21030712/3744182) and [Json.NET require all properties on deserialization](https://stackoverflow.com/a/29660550/3744182) answer your question? – dbc Mar 28 '22 at 12:49

1 Answers1

2

You could use Json.NET Schema at https://www.newtonsoft.com/jsonschema

This is from its home page:

JSchema schema = JSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'roles': {'type': 'array'}
  }
}");

JObject user = JObject.Parse(@"{
  'name': 'Arnie Admin',
  'roles': ['Developer', 'Administrator']
}");

bool valid = user.IsValid(schema);
// true
tymtam
  • 31,798
  • 8
  • 86
  • 126