[英]C# .Net Core 3.1 System.Text.Json Ignore empty collection in serialization
[英]C# System.Text.Json consider an empty object an empty array
我正在使用内置的System.Text.Json
模块解析从服务器接收到的一些 JSON 数据。
这是我将使用的示例类:
public class Something
{
[JsonPropertyName("items")]
public Item[] Items { get; set; }
}
用于此的 JSON 数据通常如下接收,并使用JsonSerializer.Deserialize<Something>()
正确解析:
{
"items": [ { ... }, { ... }, { ... } ]
}
但是,当没有项目时,服务器会返回一个空object ,这会导致异常,因为它需要一个数组。
{
"items": {}
}
有什么办法可以设置它,以便将空对象视为空数组? 我已经看到您可以制作自定义 JSON 转换器,但我很难让它工作。
在您的情况下,您不需要任何狂热的自定义转换器。 试试这个
public class Something
{
[JsonPropertyName("items")]
public object _items
{
get
{
return Items;
}
set
{
if (((JsonElement)value).ValueKind.ToString() == "Array")
{
Items = ((JsonElement)value).Deserialize<Item[]>();
}
}
}
[System.Text.Json.Serialization.JsonIgnore]
public Item[] Items { get; set; }
}
如果您不需要将其序列化,您甚至可以完全删除 _items get
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.