JsonConvert.Deserialize追加到默认属性值。如何预防呢?

我有一个.json配置文件,在其中存储应用程序设置,这些设置在应用程序启动时会反序列化。

示例:

{
    "MyProperty1": "MyValue1","MyProperty2": [1,2,3]
}

将JSON反序列化到的对象是:

public class Config{
    public string MyProperty1{ get; set; }
    public List<int> MyProperty2{ get; set; } = new List<int> { 4,5,6 };
}

我遇到的问题是,对属性MyProperty2的JSON反序列化时,它将值1,2,3附加到默认属性值4,5,6,结果是MyProperty2 = 4,5,6,1,2,3

除非在.json配置文件中另外指定,否则我希望MyProperty2缺省为4、5、6。任何帮助将不胜感激,谢谢。

happynpuzy 回答:JsonConvert.Deserialize追加到默认属性值。如何预防呢?

尝试解决Config类中的所有问题:

public class Config
{
    public Config()
    {
        this.MyProperty2 = new List<int> { 4,5,6 };
    }
    public string MyProperty1 { get; set; }
    public List<int> MyProperty2 {
        get {
            return this.MyProperty2;
        } 
        set {
            if(this.MyProperty2.Count > 0)
            {
                this.MyProperty2.Clear();
                this.MyProperty2 = value;
            }
        } 
    }
}
,

这通常对我有用: 您可能会认为,如果发出“获取”请求,它将设置默认值。如果在“获取”之前完成“设置”,则只有在“值”为null时,属性才会获取默认值。

public class Config{
    public string MyProperty1{ get; set; }

    private List<int> myProperty2{ get; set; } ;
    public List<int> MyProperty2{ 
        get{
            if (myProperty2 == null)
                myProperty2 = new List<int> { 4,6 };

            return  myProperty2 ;
        } 
        set{
            myProperty2 = value;
        } 
    } 
}
,

您可以使用JsonConvert中的Newtonsoft.Json

var setting = "{\"MyProperty1\": \"MyValue1\",\"MyProperty2\": [1,2,3]}";
var settingConfig = JsonConvert.DeserializeObject(setting);

和配置类

public class Config
{
    public string MyProperty1 { get; set; }
    [Newtonsoft.Json.JsonConverter(typeof(DefaultArrayConverter))]
    public List<int> MyProperty2 { get; set; } = new List<int> { 4,6 };
}

在这里我写了一个客户JsonConverter。

public class DefaultArrayConverter : JsonConverter
{

    public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer)
    {
        var value = serializer.Deserialize(reader,objectType);
        return value;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return false;
    }

    public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

工作正常,但我不确定为什么MyProperty2的实现中有6个值。

,

基于上述评论之一的答案,并结合我的强迫性要求,不要在此留下不可接受的答案,

假设变量json包含.json配置文件的内容:

var cfg = JsonConvert.DeserializeObject<Config>(json,new JsonSerializerSettings
{
    ObjectCreationHandling = ObjectCreationHandling.Replace
});

关键是ObjectCreationHandling-序列化程序设置ObjectCreationHandling.Replace代替默认值,而不是附加默认值。

查看更多here

本文链接:https://www.f2er.com/2933991.html

大家都在问