将JSON值存储到具有顺序键名的字典中

时间:2019-07-04 09:10:35

标签: c# json algorithm dictionary data-structures

这是一个基于How to iterate through a dictionary to get and pass key name to string的问题,下面的给定代码遍历JSON,获取键名和JArray索引并将它们有序地传递给JSON路径字符串,最后返回一个Dictionary(有序字符串, JsonValue),则字典的键名应按“ key1:key1-1:0”的顺序进行排序,这意味着requiredDictionary [“ key1:key1-1:0”] = commonDictionary [“ key1”] [“ key1-1 “] [0]。

根据以下JSON,如果 “五个”:{“ ArrayInFive”:[“ elem1”,“ elem2”]} 被删除,就可以正常工作。

C#代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
......
static void Main(string[] args)
        {
            var json = File.ReadAllText(@myJsonPath);
            var jObj = JsonConvert.DeserializeObject<JObject>(json);

            var desiredDict = FlattenJObjectToDictionary(jObj);


            foreach (var key in desiredDict.Keys)
            {
                Console.WriteLine(key + " : " + desiredDict[key]);
            }


            Console.Read();
        }

        private static IDictionary<string, string> FlattenJObjectToDictionary(JObject obj)
        {
            // obtain a key/value enumerable and convert it to a dictionary
            return NestedJObjectToFlatEnumerable(obj, null).ToDictionary(kv => kv.Key, kv => kv.Value);
        }


        private static IEnumerable<KeyValuePair<string, string>> NestedJObjectToFlatEnumerable(object data, string path = null)
        {
            JObject jObject = (JObject)data;
            var jOP = jObject.Properties();
            foreach (var jop in jOP)
            {
                if (jop.Value is JObject)
                {
                    var child = (JObject)jop.Value;

                    // build the child path based on the root path and the property name
                    string childPath = path != null ? string.Format("{0}{1}:", path, jop.Name) : string.Format("{0}:", jop.Name);

                    // get each result from our recursive call and return it to the caller
                    foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
                    {
                        yield return resultVal;
                    }
                }
                else if (jop.Value is JArray)
                {
                    var jArray = (JArray)jop.Value;
                    for (int i = 0; i < jArray.Count; i++)
                    {
                        var child = jArray[i];

                        // build the child path based on the root path and the JArray index
                        string childPath = path != null ? string.Format("{0}{1}:{2}:", path, jop.Name, i.ToString()) : string.Format("{0}:{1}:", jop.Name, i.ToString());

                        // get each result from our recursive call and return it to the caller
                        foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
                        {
                            yield return resultVal;
                        }
                    }
                }
                else
                {
                    // this kind of assumes that all values will be convertible to string, so you might need to add handling for other value types
                    yield return new KeyValuePair<string, string>(string.Format("{0}{1}", path, Convert.ToString(jop.Name)), Convert.ToString(jop.Value));
                }
            }

        }

JSON

{
    "One": "Hey",
    "Two": {
        "Two": "HeyHey"
           },
    "Three": {
        "Three": {
            "Three": "HeyHeyHey"    
                 }
              }, 
    "Four": [
            {
            "One": "Hey"
            },
            {
            "Two": 
                {
            "Two": "HeyHey"
                }
            }
            ],
    "Five": {
        "ArrayInFive": [ "elem1", "elem2" ]
            }
}

我希望

desiredDictionary [“ Five”] [“ ArrayInFive”] [0] =“ elem1”

desiredDictionary [“ Five”] [“ ArrayInFive”] [1] =“ elem2”

但是弹出了“无法将JValue转换为JObject”的例外,我需要一些有关代码校正的帮助,也许是整个程序。

1 个答案:

答案 0 :(得分:1)

将对JArray中的NestedJObjectToFlatEnumerable个对象的处理更改为:

else if (jop.Value is JArray)
{
    var jArray = (JArray)jop.Value;
    for (int i = 0; i < jArray.Count; i++)
    {
        var child = jArray[i];

        if (child is JValue)
        {
            // return JValue objects directly as array elements instead of as objects in the array with their own property-value pairs
            yield return new KeyValuePair<string, string>(string.Format("{0}{1}:{2}", path, jop.Name, i.ToString()), Convert.ToString(((JValue)child).Value));
        }
        else
        {
            // build the child path based on the root path and the JArray index
            string childPath = path != null ? string.Format("{0}{1}:{2}:", path, jop.Name, i.ToString()) : string.Format("{0}:{1}:", jop.Name, i.ToString());

            // get each result from our recursive call and return it to the caller
            foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
            {
                yield return resultVal;
            }
        }
    }
}

这通过将元素作为数组的属性(具有由数组索引给定的属性名称)返回来处理数组元素为JValue而不是具有其自身属性-值对的对象的情况到数组路径上。