【问题标题】:How to deserialize a JSON object to a dictionary with values that could be a single string or array of strings?如何将 JSON 对象反序列化为具有可能是单个字符串或字符串数​​组的值的字典?
【发布时间】: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的对象是一个类,但是这个类的属性是可变的,也就是说,我不能映射它们,因为一个属性可能不复存在或者可能添加新的属性,这是为什么我把它当作字典,因为我想在这个类的后面删除或添加参数。

【问题讨论】:

标签: c# json .net asp.net-core .net-core


【解决方案1】:

字典值不能有两种类型,如果要将它们添加到1个字典中,只能使用Dictionary<string, string[]>,并按照DavidG所说的将字符串放入string[]。或者你只能使用两个字典。这是一个演示使用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[] { };
                    }
                }

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    相关资源
    最近更新 更多