3

Assuming we have the following class:

public class Foo {
      public long Id { get; set; }
}

How can we tell newtonsoft json to throw a tantrum if a given json-string is:

{ "Id": 10, "SomethingIrrelevant": "Foobar" }

In other words we want the deserialization to be ultra-strict and throw a tantrum when it detects anything fishy of this sort taking place.

XDS
  • 3,786
  • 2
  • 36
  • 56
  • Possible duplicate of [Can I make a strict deserialization with Newtonsoft.Json?](https://stackoverflow.com/questions/22096427/can-i-make-a-strict-deserialization-with-newtonsoft-json) – dcg Mar 29 '19 at 15:30
  • Take a look at [this question](https://stackoverflow.com/q/15253875/4685428). Answer does not do exact what you want, but allow you to check if there was an extra fields after deserialization – Aleks Andreev Mar 29 '19 at 15:36

1 Answers1

5

Use MissingMemberHandling.Error for your JsonSerializerSettings:

var deserialized = JsonConvert.DeserializeObject<Foo>(jsonString,
    new JsonSerializerSettings
    {
        MissingMemberHandling = MissingMemberHandling.Error
    }); // throws with "Could not find member 'SomethingIrrelevant' on object of type 'Foo'."

You can also force it to throw if Id is not present using a JsonProperty with Required.Always:

public class Foo {
    [JsonProperty(Required = Required.Always)]
    public long Id { get; set; }
}
Jeff
  • 7,504
  • 3
  • 25
  • 34
  • I had already employed 'MissingMemberHandling' but I thought it was doing what the 'Required = Required.Always' was doing (while it was the other way around). Do you by any chance know of a way to enforce 'Required = Required.Always' via the 'JsonSerializerSettings' for all deserializations? Thank you twice Jeff! – XDS Mar 29 '19 at 16:55
  • Excellent! It would have taken days for me to find this gem! Thanks a billion! – XDS Mar 29 '19 at 19:21