Deserializing with Json.NET: Requiring a property/key to be present

后端 未结 3 1392
北海茫月
北海茫月 2020-12-20 19:20

When using Json.NET to deserialize a JSON string into an object, how do I require a key/property to be present in the JSON stirng, but allow for NULL values?

For exa

相关标签:
3条回答
  • 2020-12-20 19:39

    The real question here is: Why do you want to force the sender to set null on some values? While building an app you can never force users to behave, that's the number 1 window for hacking your app.

    Always assume users wont do what you want at some point. If that JSON comes from any other app that you own just make it send null, if its an external app or user input assume anything is possible.

    And Required doesn't mean the field is required in the input, it means it requires a value. That's your problem.

    0 讨论(0)
  • 2020-12-20 19:45

    Ugh. I should have spend a little more time in the Json.NET documentation...

    The answer is the the Required property of the JsonPropertyAttribute, which is of enum type Newtonsoft.Json.Required

    [JsonProperty(Required = Newtonsoft.Json.Required.AllowNull)]
    public string Description {get; set;}
    
    0 讨论(0)
  • 2020-12-20 19:47

    I think you are looking for the DefaultValueAttribute http://james.newtonking.com/projects/json/help/index.html?topic=html/T_Newtonsoft_Json_DefaultValueHandling.htm

    0 讨论(0)
提交回复
热议问题