C# flattening json structure

后端 未结 5 588
囚心锁ツ
囚心锁ツ 2020-12-08 07:41

I have a json-object in C# (represented as a Newtonsoft.Json.Linq.JObject object) and I need to flatten it to a dictionary. Let me show you an example of what I mean:

<
5条回答
  •  無奈伤痛
    2020-12-08 08:09

    You can use https://github.com/jsonfx/jsonfx to deserialize json into a dynamic object. Then use the ExpandoObject to get what you want.

    public Class1()
            {
                string json = @"{
                                    ""name"": ""test"",
                                    ""father"": {
                                         ""name"": ""test2"",
                                         ""age"": 13,
                                         ""dog"": {
                                             ""color"": ""brown""
                                         }
                                    }
                                }";
    
                var reader = new JsonFx.Json.JsonReader();
                dynamic output = reader.Read(json);
                Dictionary dict = new Dictionary();
    
                GenerateDictionary((System.Dynamic.ExpandoObject) output, dict, "");
            }
    
            private void GenerateDictionary(System.Dynamic.ExpandoObject output, Dictionary dict, string parent)
            {
                foreach (var v in output)
                {
                    string key = parent + v.Key;
                    object o = v.Value;
    
                    if (o.GetType() == typeof(System.Dynamic.ExpandoObject))
                    {
                        GenerateDictionary((System.Dynamic.ExpandoObject)o, dict, key + ".");
                    }
                    else
                    {
                        if (!dict.ContainsKey(key))
                        {
                            dict.Add(key, o);
                        }
                    }
                }
            }
    

提交回复
热议问题