【发布时间】:2019-01-30 11:45:44
【问题描述】:
我想跳过一些与默认值相同的字典值。
这是该词典的简化代码
public Dictionary<int, Item> allItems;
public class Item
{
public bool IsSelected;
public List<string> SelectionInfo;
}
所以,截至目前,我的 JSON 输出如下所示:
"allItems": {
"0": {
"IsSelected": true,
"SelectionInfo": [
"yes",
"maybe",
"no"
]
},
"1": {
"IsSelected": false,
"SelectionInfo": []
}
}
我想跳过“1”但不要完全跳过它,至少保留密钥以便以后可以恢复。并在字典上有 0 和 1
像这样?
"allItems": {
"0": {
"IsSelected": true,
"SelectionInfo": [
"yes",
"maybe",
"no"
]
},
"1": { }
}
我环顾四周,发现您可以使用 JsonConverter。但是我的案例 JSON 工具在另一个项目 (Utility.Please.TurnToJson(item);) 上,我想保持它的一致性,并且在所有项目中只使用一个 JSON。也许如果 JsonConverter 是唯一的选择,至少为我提供有关如何将自定义 JsonConverter 传递给该项目的解决方案。
///somewhat like this?
Utility.Please.TurnToJson(item, new List<object>(){
typeof(Custom1),
typeof(Custom2)
});
【问题讨论】:
-
那么您的预期输出结果如何?
-
@er-mfahhgk 我更新了想要的结果。
-
那么我们如何决定只保留它的密钥呢?它基于
SelectionInfo数组是空的还是IsSelected是假的? -
@er-mfahhgk 两者。如果 IsSelected 为 false 且列表为空!
-
若要在值为 false 时跳过
IsSelected的序列化,请设置[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)],如Is there an alternative forShouldSerialize[PropertyName]in C#? 所示。要在集合为空时跳过序列化,请参阅Can Newtonsoft Json.NET skip serializing empty lists? 和/或How to make Json.Net skip serialization of empty collections。事实上,这可能是这三个的副本。同意吗?
标签: c# dictionary uwp json.net