简体   繁体   中英

Converting dictionary in a complex Json to list<string>

I have a JSON string that contains both dictionary as well as list For parsing, there exists a function which converts the list type from the JSON string to dictionary. I need to write a function that will convert Dictionary type to List type. What will be the most efficient way to do this?

For example...

Suppose this is my sample json string -

"{\"foo1\":{\"0\":\"0\",\"1\":\"S\",\"2\":\"S\",\"3\":\"J\",\"4\":\"Q\",\"5\":\"X\",\"6\":\"M\"},\"foo2\":{\"1\":\"one\" ,\"2\":\"two\",\"4\":\"four\",\"5\":\"five\",\"6\":\"six\",\"7\":\"seven\",\"8\":\"eight\"}"

Which is an efficient way to take the dictionary values from here and convert them to list of strings.

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
    class Program
    {

        static void Main(string[] args)
        {
            string JSONIncludeBackslash = "{\"foo1\":{\"0\":\"0\",\"2\":\"S\",\"3\":\"J\",\"4\":\"Q\",\"5\":\"X\",\"6\":\"M\"},\"foo2\":{\"1\":\"one\",\"7\":\"seven\",\"8\":\"eight\"}}";
            Dictionary<string, string> JSONDictionary = JSONIncludeBackslash.Replace("\"", "").Replace(":{", "*").Replace("},", ",").Replace("}}", "").Replace("{", "").Replace("}", "").Split(',').ToDictionary(value => { return value.Split(':')[0].IndexOf("*") > -1 ? value.Split(':')[0].Split('*')[1] : value.Split(':')[0]; });

            Dictionary<string, string> JSONDictionary1 = JSONIncludeBackslash.Replace("\"", "").Replace(":{", "*").Replace("},", ",").Replace("}}", "").Replace("{", "").Replace("}", "").Split(',').ToDictionary(value => { return value.Split(':')[0].IndexOf("*") > -1 ? value.Split(':')[0].Split('*')[1] : value.Split(':')[0]; });
            foreach (var Entry in JSONDictionary1)
            {
                JSONDictionary[Entry.Key] = Entry.Value.Split(':')[1];
            }

            IList<KeyValuePair<string, string>> JSONList = JSONDictionary.ToList();
            foreach (var Item in JSONList)
            {
                Console.WriteLine(Item);
            }
            Console.ReadLine();
        }
    }
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM