JSON.net, C#, unable to set default values in data model

雨燕双飞 提交于 2019-12-05 22:46:09

You are using the wrong setting.

If you want null values in the JSON to be ignored during deserialization, you need to set NullValueHandling = NullValueHandling.Ignore in the settings. The default is Include, which means that if the JSON has an explicit null in it for a particular property, that property will be set to null on your object, overwriting any default you may have set.

DefaultValueHandling.Populate means if the key is missing altogether in the JSON (which is different from being set to null), then it will use the value provided by the [DefaultValue] attribute. Note that if the JSON has an explicit null in it, this setting will not use the default value from the attribute, even if NullValueHandling is set to Ignore. So if you want a default value in that situation, the best way to do that is by setting it in the constructor.

So, in short, to get the behavior you want:

  • Use the NullValueHandling.Ignore setting.
  • Provide your default values via the constructor.
  • You don't need the DefaultValueHandling setting or the [DefaultValue] attribute.

Demo fiddle: https://dotnetfiddle.net/kyUjFz

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