Detect if deserialized object is missing a field with the JsonConvert class in Json.NET
The Json.Net serializer has a MissingMemberHandling
setting which you can set to Error
. (The default is Ignore
.) This will cause the serializer to throw a JsonSerializationException
during deserialization whenever it encounters a JSON property for which there is no corresponding property in the target class.
static void Main(string[] args)
{
try
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MissingMemberHandling = MissingMemberHandling.Error;
var goodObj = JsonConvert.DeserializeObject<MyJsonObjView>(correctData, settings);
System.Console.Out.WriteLine(goodObj.MyJsonInt.ToString());
var badObj = JsonConvert.DeserializeObject<MyJsonObjView>(wrongData, settings);
System.Console.Out.WriteLine(badObj.MyJsonInt.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
}
Result:
42
JsonSerializationException: Could not find member 'SomeOtherProperty' on object
of type 'MyJsonObjView'. Path 'SomeOtherProperty', line 3, position 33.
See: MissingMemberHandling setting.
Just add [JsonProperty(Required = Required.Always)]
to the required properties and it'll throw exception if the property is not there while deserializing.
[JsonProperty(Required = Required.Always)]
public int MyJsonInt { get; set; }
Put the following attribute on required properties:
[DataMember(IsRequired = true)]
If the member is not present, it will throw a Newtonsoft.Json.JsonSerializationException.
As Brian suggested below, you will also need this attribute on your class:
[DataContract]