我正在使用JSON.Net将数据库中的数据序列化为JSON格式。但是我无法获得预期的结果。
我必须根据某些条件来创建JSON对象,例如如果datamap
的数据为空,则不应将其包含在JSON中;如果不为空,则应将其包含在内。
public class DatamapKey
{
[JsonExtensionData]
public Dictionary<string, JToken> DatamapKeyFields = new Dictionary<string, JToken>();
}
public class DatamapKey1
{
[JsonExtensionData]
public Dictionary<string, JToken> DatamapKey1Fields = new Dictionary<string, JToken>();
}
public class DatamapItem
{
[JsonExtensionData]
public Dictionary<string, JToken> DatamapItemFields = new Dictionary<string, JToken>();
public DatamapKey datamapKey { get; set; }
public DatamapKey1 datamapKey1 { get; set; }
}
public class RootObject
{
public List<DatamapItem> datamapItems { get; set; }
}
输出JSON:
{
"datamapItems": [
{
"datamapKey": {
"module": 1,
"id": 1391
},
"datamapKey1": {},
"paramName": "VE8321C",
"min": "0",
"max": "40"
},
{
"datamapKey": {},
"datamapKey1": {},
"paramName": "VE8321C",
"min": "0",
"max": "40"
},
{
"datamapKey": {
"module": 1,
"id": 1391
},
"datamapKey1": {
"module": 1,
"id": 1391
},
"paramName": "VE8321C",
"min": "0",
"max": "40"
}
]
}
预期输出:
{
"datamapItems": [
{
"paramName": "VE8321C",
"datamapKey": {
"module": 1,
"id": 1391
},
"min": "0",
"max": "40"
},
{
"paramName": "VE8321C",
"min": "0",
"max": "40"
},
{
"paramName": "VE8321C",
"datamapKey": {
"module": 1,
"id": 1391
},
"datamapKey1": {
"module": 1,
"id": 1391
},
"min": "0",
"max": "40"
}
]
}
答案 0 :(得分:3)
[JsonExtensionData]
属性使标记的字典中的键/值对被序列化,就好像它们是包含该字典的类的属性一样。该属性由Json.Net专门处理,因此@Alex在注释中建议的IgnoreEmptyEnumerablesResolver
对此无效。但是您可以重组类,这样就不需要datamapKey
和datamapKey1
的属性,这将使解析器在这些字典为空时可以对其进行处理,从而为您提供所需的输出
public class DatamapItem
{
[JsonExtensionData]
public Dictionary<string, JToken> DatamapItemFields { get; set; } = new Dictionary<string, JToken>();
public Dictionary<string, JToken> datamapKey { get; set; } = new Dictionary<string, JToken>();
public Dictionary<string, JToken> datamapKey1 { get; set; } = new Dictionary<string, JToken>();
}
public class RootObject
{
public List<DatamapItem> datamapItems { get; set; }
}
演示小提琴:https://dotnetfiddle.net/Gw03gY
如果您不喜欢该主意或不想修改您的类结构,另一种选择是将对象实例加载到JObject
中,并使用递归方法从层次结构中删除空标记。 How to omit/ignore/skip empty object literals in the produced JSON?中详细介绍了此方法。
下面是一个演示小提琴,用您现有的类结构显示了该方法:https://dotnetfiddle.net/jmNgYi