0

It's a C# console app, I'd like to make JSON interact with a Dictionary by passing keys separated by colon, the keys of the dictionary are expected to be passed in the form of "key1:key1-1:key1-1-1", the path of keys is fixed like that, so I'm told not to use outer string-manipulating functions.

I've stored my JSON data into C# string.

Here is my sample JSON

{
    "One": "Hey",

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

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

"HeyHeyHey" shall be the expected value for dictionary["Three:Three:Three"] according to the sample JSON. How do I store JSON data into a Dictionary in the form of dictionary["Three:Three:Three"], not dictionary["Three"]["Three"]["Three"]. I thought of using string-manipulating functions to operate on JSON keys, but I'm told that the program will not call my functions.

Chen
  • 171
  • 3
  • 14
  • 1
    It seems like you are reinventing [tag:jsonpath] syntax. See https://goessner.net/articles/JsonPath/. Why do that, when [tag:json.net] (the most commonly used JSON parser in .Net) already supports it via [`SelectToken`](https://www.newtonsoft.com/json/help/html/SelectToken.htm)? – dbc Jul 02 '19 at 08:00
  • 1
    Alternatively, maybe you want something like this? [How do I convert a JSON object into a dictionary with Path being the key](https://stackoverflow.com/q/27749114/3744182). – dbc Jul 02 '19 at 08:05

1 Answers1

1

If you use Newtonsoft.Json you can do it like this.

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());
    }
}
Mikhail
  • 38
  • 4