c# - 如何使用 JSON.NET 将带有空值的 json 数组反序列化为不可空的 int 列表?

标签 c# json json.net

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

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

我正在尝试反序列化为以下属性:

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);

关于c# - 如何使用 JSON.NET 将带有空值的 json 数组反序列化为不可空的 int 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72460627/

相关文章:

c# - 如何使用一个StreamWriter写入多个底层流?

c# - 在 Winforms 中绘制 CachedBitmap

c# - 如何在 Elasticsearch NEST 中序列化 JToken 或 JObject 类型的属性?

c# - IdentityServer4/Newtonsoft.Json 中的探查器 BLOCKED_TIME

c# - Visual Studio 2017 控制台未显示但正在运行

c# - Wpf Datagrid 在绑定(bind)时不显示一列

从 String 中提取 ID 的 Java regex 和/或 string magic

javascript - 在 JSON 文件中搜索。

javascript - 所选字段或参数(名称)的 JSON 和 PHP 数据检索

c# - JSON Newtonsoft C# - 反序列化 JSON 文件中的特定字段