gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:27:24 27 4
gpt4 key购买 nike

我有以下 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com