0

这是示例代码:

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

我想做的是从 JSON 反序列化,其中包含一个包含七个错误值的列表。但是,在反序列化它时,它似乎构造了一个包含 14 个值的列表,其中包括默认值,并像这样附加了从 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

4

1 回答 1

0

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

如果您想要替换默认列表并继续使用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]}]");
        ...
    }
...
}
于 2021-02-06T23:47:31.223 回答