【发布时间】:2021-05-16 08:57:14
【问题描述】:
我有一个 JSON 对象,这个 JSON 的一个属性是一个可以接收字符串值或字符串值数组的字典。
我的问题是:是否可以使用带有条件泛型参数的字典来处理这种情况,例如:Dictionary<string, string || string[]>?
因为我需要反序列化一个字典中的值。
以下是 JSON 对象的示例,其中clientContent 需要映射到这样的字典:
"clientConfDesc": {
"clientContent": {
"app.log.mail.port": "",
"app.log.mail.protocol": "",
"app.log.mail.receiver": "",
"app.log.mail.server": "",
"app.lookupDaemon.interval": "",
"app.lookupDaemon.use": "yes",
"app.remoteCall.ttl": "",
"app.typeDef": ["5, , PD, PEDIDO"]
}
}
注意:我知道这个例子JSON的对象是一个类,但是这个类的属性是可变的,也就是说,我不能映射它们,因为一个属性可能不复存在或者可能添加新的属性,这是为什么我把它当作字典,因为我想在这个类的后面删除或添加参数。
【问题讨论】:
-
如果数组中的单个值也可用,您会高兴吗?所以你可以使用
Dictionary<string, string[]>? -
另外,您确定 JSON 中的最后一行是正确的吗?它是否意味着是数组中的单个字符串?
-
c# 并没有很好地支持像 f# discriminated union 这样的联合类型。在 c# 中,将
clientContent反序列化为Dictionary<string, List<string>>并在反序列化期间将单个字符串值映射到包含单个字符串的列表将是最简单的。 -
但是您使用的是什么序列化程序? json.net 还是 system.text.json?如果您使用的是json.net,则可以使用How to handle both a single item and an array for the same property using JSON.net 中的
SingleOrArrayConverter<string>。如果您使用的是system.text.json,您可以使用How to handle both a single item and an array for the same property using System.Text.Json? 中的SingleOrArrayConverterFactory。
标签: c# json .net asp.net-core .net-core