c# - 将 JSON 值存储到具有有序键名的字典中

标签 c# json algorithm dictionary data-structures

这是一个基于How to iterate through a dictionary to get and pass key name to string的问题,下面给定的代码遍历一个 JSON,获取键名和 JArray 索引并将它们有序地传递给 JSON 路径的字符串,最后它返回一个字典(有序字符串,JsonValue),字典键名应该像这样排序“key1:key1-1:0”,表示 desiredDictionary["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”的异常,我需要一些代码更正方面的帮助,也许是整个程序。

最佳答案

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

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 而不是具有自己的属性值对的对象的情况,方法是将元素作为数组的属性返回,属性名称由数组给出索引(连接到数组路径上)。

关于c# - 将 JSON 值存储到具有有序键名的字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56884455/

相关文章:

java - 如何将 JSON 字符串转换为带有属性的 xml?

c# - EF Core - 等效于 IQueryable 搜索的表达式树

c# - 打开目标类型未知的实例委托(delegate)?

java - 如何访问 LinkedHashMap 中嵌套对象的数据

java - 如何让 jackson 使用一种方法将类序列化为 JSON?

algorithm - 具有相关索引的三重嵌套 Big O

algorithm - 如果 n > 3,求关系 T (n) =T (n-1)+T(n-2)+T(n-3) 的时间复杂度

algorithm - 《地下城守护者 2》风格 map ,顶点压缩

c# - 如何添加实际等待?

c# - 为什么嵌套字典的反序列化在 C# 中引发异常但在 F# 中有效?