1. JSON has a property that is not in your class
Using the JsonSerializerSettings.MissingMemberHandling property, you can tell if missing properties are treated as errors.
Than you can install the Error delegate, which will log errors.
This will detect if there is any โgarbageโ property in the JSON string.
public class ClassA { public int Id { get; set; } public string SomeString { get; set; } } internal class Program { private static void Main(string[] args) { const string str = "{'Id':5, 'FooBar': 42 }"; var myObject = JsonConvert.DeserializeObject<ClassA>(str , new JsonSerializerSettings { Error = OnError, MissingMemberHandling = MissingMemberHandling.Error }); Console.ReadKey(); } private static void OnError(object sender, ErrorEventArgs args) { Console.WriteLine(args.ErrorContext.Error.Message); args.ErrorContext.Handled = true; } }
2. Your class has a property that is not in JSON
Option 1:
Make it mandatory:
public class ClassB { public int Id { get; set; } [JsonProperty(Required = Required.Always)] public string SomeString { get; set; } }
Option 2:
Use some โspecialโ value as the default value and then check it.
public class ClassB { public int Id { get; set; } [DefaultValue("NOTSET")] public string SomeString { get; set; } public int? SomeInt { get; set; } } internal class Program { private static void Main(string[] args) { const string str = "{ 'Id':5 }"; var myObject = JsonConvert.DeserializeObject<ClassB>(str , new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Populate }); if (myObject.SomeString == "NOTSET") { Console.WriteLine("no value provided for property SomeString"); } Console.ReadKey(); } }
Option 3:
Another good idea would be to encapsulate this check as an istself class. Create the Verify() method as shown below and call it after deserialization.
public class ClassC { public int Id { get; set; } [DefaultValue("NOTSET")] public string SomeString { get; set; } public int? SomeInt { get; set; } public void Verify() { if (SomeInt == null ) throw new JsonSerializationException("SomeInt not set!"); if (SomeString == "NOTSET") throw new JsonSerializationException("SomeString not set!"); } }
source share