如何使用Newtonsoft JSON序列化器忽略空数组元素 [英] How to ignore null array elements with Newtonsoft JSON serializer
问题描述
我正在尝试序列化对象数组,但是我需要它忽略空元素.我意识到我可以在反序列化时简单地拥有检查空值的逻辑,但是我不想在网络上写入不必要的数据.该数组最多可包含9个元素,但并非在所有实例中都使用所有9个索引.我知道可以使用列表,但是出于效率考虑,我不希望这样做.
I'm attempting to serialize an object array, but I need it to ignore null elements. I realize I could simply have logic upon deserialization that checks for the nulls, however I don't want to write unnecessary data over the network. The array can have a maximum of 9 elements, but all 9 indices are not used in every instance. I understand that a list could be utilized, but for efficiency sake I do not wish to do that.
对于我在该网站上浏览过的类似问题,我试图将以下标签添加到数组中: [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
Per similar questions I've browsed on this site, I've attempted to add the following tag to the array: [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
但是,这种方法不会忽略null元素.
However, this approach does not ignore null elements.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Node[] Nodes { get; }
public void Init()
{
Nodes = new Node[9];
}
public string Encode()
{
return JsonConvert.SerializeObject(Nodes, Formatting.None);
}
是否有一个优雅的解决方案?
Is there an elegant solution to this?
推荐答案
最简单的解决方案是在序列化之前过滤数组.您可以在您的 Encode
方法中执行此操作,而无需实例化新数组:
The simplest solution is just to filter the array just before you serialize it. You can do this in your Encode
method, without instantiating a new array:
public string Encode()
{
return JsonConvert.SerializeObject(Nodes.Where(n => n != null), Formatting.None);
}
提琴: https://dotnetfiddle.net/dj8lnP
如果您不喜欢该主意,无论出于何种原因,都可以使用自定义序列化为JSON时不包含集合中的特定项类似进行过滤.
If you don't like that idea, for whatever reason, you can use a custom JsonConverter
similar to the one in Excluding specific items in a collection when serializing to JSON to do the filtering.
这篇关于如何使用Newtonsoft JSON序列化器忽略空数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!