我有一个 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的对象是一个类,但是这个类的属性是可变的,也就是说,我无法映射它们,因为一个属性可能不存在或者可能会添加新的属性,这就是为什么我对待将这种情况作为字典,因为我想稍后在该类中删除或添加参数。
字典值不能有两种类型,如果要将它们添加到1个字典中,则只能使用Dictionary<string, string[]>
,并将字符串放入string[]
DavidG所说的。或者您只能使用两个字典。这是一个使用演示Dictionary<string, string[]>
。
这是一个演示:
楷模:
public class Model1
{
public Model2 clientConfDesc { get; set; }
}
public class Model2
{
public Dictionary<string, string[]> clientContent { get; set; }
}
测试数据:
{
"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"]
}
}
}
代码:
var mydata = JsonConvert.DeserializeObject<JObject>(json);
var obj= JsonConvert.DeserializeObject<JObject>(mydata["clientConfDesc"]["clientContent"].ToString());
var model = new Model1 { clientConfDesc = new Model2 { clientContent = new Dictionary<string, string[]>() } };
foreach (var item in obj)
{
var s=item.Value.ToString();
if (s.Contains("["))
{
model.clientConfDesc.clientContent[item.Key] = JsonConvert.DeserializeObject<string[]>(s);
}
else if (s != "")
{
model.clientConfDesc.clientContent[item.Key] = new string[] { s };
}
else {
model.clientConfDesc.clientContent[item.Key] = new string[] { };
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句