JSON.net,C#,无法在数据模型中设置默认值 [英] JSON.net, C#, unable to set default values in data model

查看:386
本文介绍了JSON.net,C#,无法在数据模型中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JsonConvert.DeserializeObject(json.ToString()); 反序列化JSON并在相关模型中填充我的字段.直到JSON中缺少数据为止,此方法都可以正常工作.基本上没有"key:value",而只有"key:null".

I am using JsonConvert.DeserializeObject(json.ToString()); to deserialise a JSON and populate my fields in a related model. This works well until there is data missing in the JSON. Basically instead of having "key : value" I will just have "key : null".

我对JsonConverter的理解是,它将创建一个对象,在该对象中,我应该能够通过构造函数(由于未知原因而不会被我调用)或通过标记来填充具有默认值的字段.在这里提到:缺少JSON.net属性的默认值或此处:为什么当我使用JSON反序列化时. NET会忽略我的默认值?

My understanding about the JsonConverter was that it would create an object, in which I should be able to populate fields with a default value either through the constructor (not being called in my case for unknown reasons), or through the tags as mentioned here: Default value for missing properties with JSON.net or here: Why when I deserialize with JSON.NET ignores my default value?

我已经尝试了两种方法,但都没有初始化相关字段的结果. 当然,如果JSON中没有数据,则无法将任何数据反序列化到相关模型.但是我希望我仍然可以使用默认值来初始化一些值,然后这些值将被JsonConverter忽略(不会被覆盖)(就像现在发生的一样).但是,这似乎不可能吗?

I have tried both and neither results in the related fields being initialised. Of course if there is no data in the JSON, nothing can be deserialised to the related model. However I would expect that I still could initialise some values with defaults, which would then just be ignored (not overwritten) by JsonConverter (just like what happens now). This however, does not seem to be possible?

先前尝试的源代码

模型类

Model class

namespace Project.MyJob
{
    public class JsonModel
    {
        public JsonModel()
        {
            Type_X type_x = new Type_X();
            // This is not doing anything. I would have expected that the 
            // class' constructor would be called but, no.
        }
        public string objectNumber { get; set; }
        public string objectFamily { get; set; }
        public string objectOrder { get; set; }
        public string location { get; set; }
        public string place { get; set; }
        public string inventionTime { get; set; }
        public string lastUpdate { get; set; }
        public string condition { get; set; }

        public Type_X Type_X { get; set; }
        public List<Actions> actions { get; set; }         
    }

    public class Actions
    {
        public string count { get; set; }
        public string datetime { get; set; }
        public string place { get; set; }
        public string status { get; set; }
    }

    public class Type_X
    {  

        public Type_X
        {
          // This should be executed when a new Type_X object is created? Also 
          // not.
          partA = "null";
        }

        [DefaultValue("null")]
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        public string partA { get; set; }

        // Trying public string partA { get; set; } = "null"; also does 
        // nothing.

        [DefaultValue("null")]
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        public string PartB { get; set; }

        [DefaultValue("null")]
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        public string partC { get; set; }

        [DefaultValue("null")]
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        public string partD { get; set; }

        [DefaultValue("null")]
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
        public string partE { get; set; }
    }
}

使用默认值(默认设置无效)创建JSON对象

Creation of JSON object with default values (defaults not working)

JObject = JsonConvert.DeserializeObject<JsonModel>(json.ToString(), new 
JsonSerializerSettings {DefaultValueHandling = 
DefaultValueHandling.Populate});

所创建对象的下游用法示例

Example of downstream usage of the created objects

JObject.actions[i].count + "more text"

在不依赖默认值的情况下,上述方法有效.

Above works when not relying on defaults.

推荐答案

您使用了错误的设置.

You are using the wrong setting.

如果要在反序列化期间忽略JSON中的null值,则需要在设置中设置NullValueHandling = NullValueHandling.Ignore.默认值为Include,这意味着,如果JSON中具有特定属性的显式null,则该属性将在您的对象上设置为null,从而覆盖您可能设置的任何默认值.

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表示如果JSON中的键完全丢失(与设置为null不同),则它将使用[DefaultValue]属性提供的值.请注意,如果JSON中包含显式的null,则即使NullValueHandling设置为Ignore,此设置也将使用属性中的默认值.因此,如果您想在这种情况下使用默认值,最好的方法是在构造函数中进行设置.

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:

  • 使用NullValueHandling.Ignore设置.
  • 通过构造函数提供默认值.
  • 您不需要DefaultValueHandling设置或[DefaultValue]属性.
  • Use the NullValueHandling.Ignore setting.
  • Provide your default values via the constructor.
  • You don't need the DefaultValueHandling setting or the [DefaultValue] attribute.

演示小提琴: https://dotnetfiddle.net/kyUjFz

这篇关于JSON.net,C#,无法在数据模型中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆