Reputation: 1574
I'm using MissingMemberHandling = MissingMemberHandling.Error,
in order to throw an error when there is a property in the JSON and no corresponding property in my C# class.
That works.
In addition to that, I want it to throw an error when there is a property in my class but not in the JSON.
How can I do that?
Upvotes: 0
Views: 2628
Reputation: 18155
You could make use of JsonObjectAttribute
with ItemRequired
set to Required.Always
..
[JsonObject(ItemRequired = Required.Always)]
For example,Assuming User Class
is defined as
[JsonObject(ItemRequired = Required.Always)]
public class User
{
public string Name{get;set;}
public int Age{get;set;}
}
If you attempt to deserialize a Json without the Age Property, for example
var json = @"{
'Name':'John Doe',
}";
var result = JsonConvert.DeserializeObject<User>(json);
You would recieve an JsonSerializationException
Required property 'Age' not found in JSON. Path ''
Upvotes: 2