【问题标题】:How to retrieve and store JSON data in a Dictionary by providing keys separated by colon ":"如何通过提供以冒号“:”分隔的键来在字典中检索和存储 JSON 数据
【发布时间】:2019-07-02 07:44:47
【问题描述】:

这是一个 C# 控制台应用程序,我想通过传递以冒号分隔的键来使 JSON 与字典交互,字典的键应以“key1:key1-1:key1-”的形式传递1-1",键的路径是这样固定的,所以我被告知不要使用外部字符串操作函数。

我已将 JSON 数据存储到 C# 字符串中。

这是我的 JSON 示例

{
    "One": "Hey",

    "Two": {
               "Two": "HeyHey"
           }

    "Three": {
                 "Three": {
                              "Three": "HeyHeyHey"  
                          }
             } 
}

"HeyHeyHey" 应为根据示例 JSON 的 dictionary["Three:Three:Three"] 的预期值。 如何以字典 ["Three:Three:Three"] 的形式将 JSON 数据存储到字典中,而不是字典 ["Three"]["Three"]["Three"]。 我想过使用字符串操作函数来操作 JSON 键,但我被告知程序不会调用我的函数。

【问题讨论】:

标签: c# json class dictionary


【解决方案1】:

如果你使用 Newtonsoft.Json,你可以这样做。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Dictionary<string, string> dic = new Dictionary<string, string>();

string js = @"{ ""One"": ""Hey"", ""Two"": { ""Two"": ""HeyHey"" }, ""Three"": { ""Three"": { ""Three"": ""HeyHeyHey"" } } }";

dynamic d = JObject.Parse(js);

CreateDictionary(d, "");

private void CreateDictionary(dynamic d, string key)
{
    PropertyDescriptorCollection properties = (d as ICustomTypeDescriptor).GetProperties();
    foreach (PropertyDescriptor pd in properties)
    {
        if (d[pd.Name].Value == null)
            CreateDictionary(d[pd.Name], key + pd.Name + ":");
        else
            dic.Add(key + pd.Name, d[pd.Name].Value.ToString());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2012-01-29
    • 2022-01-07
    • 2013-06-23
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    相关资源
    最近更新 更多