问题
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.
回答1:
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; }
}
来源:https://stackoverflow.com/questions/55420732/newtosoft-json-deserialization-how-to-throw-an-error-if-when-the-given-json-str