【问题标题】:Newtonsoft JsonConvert DeserializeObject cannot ignore Default Value from entity err?Newtonsoft JsonConvert DeserializeObject 不能忽略实体错误的默认值?
【发布时间】:2021-02-06 21:41:24
【问题描述】:

这里是示例代码:

我有一个包含布尔列表的 TargetEntity,默认情况下,它设置为 true 值的七元素列表。

我要做的是从 JSON 反序列化,其中包含一个包含七个 false 值的列表。 然而,在反序列化它时,它似乎构建了一个包含 14 个值的列表,其中包括默认值和 attached 从 JSON 中反序列化的值,例如 { true, true, true, true, true, true, true, false, false, false, false, false, false, false } 这里有什么问题?

using Newtonsoft.Json;
using System.Collections.Generic;


public class Program
{
    public static void Main()
    {
        var _entityList = JsonConvert.DeserializeObject<List<TargetEntity>>(
            "[{\"BoolsList\": [false,false,false,false,false,false,false]}]",
            new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });

        Console.WriteLine("List size: " + _entityList[0].BoolsList.Count);

        for(int i = 0; i < _entityList[0].BoolsList.Count; i++)
        {
            Console.WriteLine($"List element {i}: " + _entityList[0].BoolsList[i]);
        }
        
    }

    public class TargetEntity 
    {
        public List<bool> BoolsList { get; set; } = new List<bool> { true, true, true, true, true, true, true };
    }

}

此代码有类似 C# 的小提琴:https://dotnetfiddle.net/VMIXeg

【问题讨论】:

    标签: json.net jsonconverter


    【解决方案1】:

    这是一个非常有趣的行为,与序列化程序设置以及新对象的构造和填充方式有关 :)

    如果您想要替换默认列表并继续使用Newtonsoft.Json,您可以替换设置

    new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }
    

    通过

    new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }
    

    根据您的 .NET 版本,您也可以使用System.Text.Json

    using System;
    using System.Collections.Generic;
    using System.Text.Json;
    
    public class Program
    {
        public static void Main()
        {
            var _entityList = JsonSerializer.Deserialize<List<TargetEntity>>("[{\"BoolsList\": [false,false,false,false,false,false,false]}]");
            ...
        }
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多