Detecting mismatched objects with Newtonsoft.Json
A common issue in API client libraries is mismatches between the JSON response and the expected strongly typed objects. I encountered this with TMDbLib and created a validator to catch these mismatches during unit testing. The Settings We can set up a JsonSerializerSettings object to: Treat missing properties as errors. Use a custom ContractResolver to enforce that all expected properties must exist in the JSON. Handle and log deserialization errors without throwing immediately. private static readonly List<ErrorEventArgs> Errors = new List<ErrorEventArgs>(); public static void Main() { JsonSerializerSettings settings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error, ContractResolver = new FailingContractResolver(), Error = Error }; JsonSerializer serializer = JsonSerializer.Create(settings); } private static void Error(object sender, ErrorEventArgs errorEventArgs) { Errors.Add(errorEventArgs); errorEventArgs.ErrorContext.Handled = true; } This configuration makes sure that: ...