Newtosoft Json Deserialization: How to throw an error if/when the given json string has MORE properties than necessary?

折月煮酒 提交于 2020-02-05 05:31:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!