Reputation: 181
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.
Upvotes: 0
Views: 452
Reputation: 48
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());
}
}
Upvotes: 1