Search code examples
c#jsonjson.net

Throwing exception on deserializing type/naming-faulty JSON?


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.


Solution

  • 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