Сохранение значения JSON в словарь с упорядоченным именем ключа - PullRequest
1 голос
/ 04 июля 2019

Это вопрос, основанный на Как перебирать словарь для получения и передачи имени ключа в строку , приведенный ниже код перебирает JSON, получая имена ключей и индекс JArray и передавая их упорядоченнок строкам путей JSON, наконец, он возвращает словарь (упорядоченная строка, JsonValue), ключ-имя словаря, как ожидается, будет упорядочен как «ключ1: ключ1-1: 0», что означает требуемый словарь [»ключ1: ключ1-1:0 "] = commonDictionary [" key1 "] [" key1-1 "] [0].

В соответствии с JSON ниже, если" Five ": {" 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" ]
            }
}

Iожидаем

wantedDictionary ["Five"] ["ArrayInFive"] [0] = "elem1"

и

wantedDictionary ["Five"] ["ArrayInFive"] [1] = "elem2"

Но за исключением того, что "невозможно конвертировать JValue в JObject", мне нужна помощь с исправлением кода, может быть, всей программы.

1 Ответ

1 голос
/ 05 июля 2019

Измените вашу обработку 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 вместо объекта со своим собственным свойством-значениемпар, возвращая элемент как свойство массива с именем свойства, заданным индексом массива (сцепленным на путь массива).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...