这是示例代码:
我有一个包含 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