json的以下部分给我带来了麻烦:

"edges":["5","","5",""]}

我正在try 将其反序列化为以下属性:

public class Redacted
{
    ...

    [JsonProperty("edges", NullValueHandling = NullValueHandling.Ignore)]
    public List<int> Edges { get; set; } = new();

    ...
}

然而,这给了我以下错误:

Newtonsoft.Json.JsonSerializationException
  HResult=0x80131500
  Message=Error converting value {null} to type 'System.Int32'. Path 'edges[1]', line 1, position 186.
  Source=Newtonsoft.Json
  StackTrace:
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Populate(JsonReader reader, Object target)
   at REDACTED.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer) in REDACTED.cs:line 45

  This exception was originally thrown at this call stack:
    System.Convert.ChangeType(object, System.Type, System.IFormatProvider)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(Newtonsoft.Json.JsonReader, object, System.Globalization.CultureInfo, Newtonsoft.Json.Serialization.JsonContract, System.Type)

Inner Exception 1:
InvalidCastException: Null object cannot be converted to a value type.

我试图在模型中指定NullValueHandling.Ignore,但这似乎只适用于属性,而不适用于列表中的项目.

我宁愿不必在设置中设置NullValueHandling.Ignore,它应该只适用于此特定属性.

如何将此json反序列化为List<int>

推荐答案

因为您使用的是Json.NET中,您可以构建一个自定义转换器来处理空的string并将其转换为int.这是一个开始:

public class NullableStringToIntConverter : JsonConverter
{
    public override bool CanConvert(Type objectType) => typeof(List<string>) == objectType;

    public override object ReadJson(JsonReader reader, Type objectType,
        object existingValue, JsonSerializer serializer)
    {
        var items = serializer.Deserialize<List<string>>(reader);
        
        return items
            .Where(s => !string.IsNullOrEmpty(s))
            .Select(int.Parse)
            .ToList();
            
        throw new NotImplementedException();
    }

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

要反序列化到的类将如下所示:

public class Thing
{
    [JsonConverter(typeof(NullableStringToIntConverter))]
    public List<int> Edges { get; set; }
}

最后要反序列化:

var thing = JsonConvert.DeserializeObject<Thing>(json);

Csharp相关问答推荐

在依赖性注入和继承之间进行 Select

MongoDB将JS查询转换为C#的问题

什么是通过反射创建类的泛型接口方法的正确方法?

我需要两个属性类吗

此反射有什么问题.是否发送值转换委托?

MongoDB.NET-将数据绑定到模型类,但无法读取整数值

如何将不同类型的扩展参数的javascript函数转换成C#风格?

TCPClient阅读流

Docker Container中的HttpRequest后地址不可用

如何在C#中创建VS代码中的控制台应用程序时自动生成Main方法

VS 2022 for ASP.NET Core中缺少自定义项模板

在.NET 8最低API中从表单绑定中排除属性

如何从Azure函数使用Graph API(SDK 5.35)中的[FindMeetingTimes]

当我手动停止和关闭系统并打开时,Windows服务未启动

Azure函数正在返回值列表,但该列表在Chrome中显示为空

如何设置WinForms按钮焦点,使其看起来像是被Tab键插入其中?

如何消除Visual Studio错误,因为它不识别集合表达式的新C#12语法?

仅在Blazor Web App中覆盖生产的基本路径(.NET8中的_Hosts.cshtml文件功能?)

我想我必须手动使用res1(字符串形式的PowerShell哈希表)

具有双返回类型的多路委托,仅返回最后一个方法';S结果,而不是所有方法';S结果