简体   繁体   English

将复杂的Json中的字典转换为列表<string>

[英]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. 我有一个既包含字典又包含列表的JSON字符串。为了进行解析,存在一个将列表类型从JSON字符串转换为字典的函数。 I need to write a function that will convert Dictionary type to List type. 我需要编写一个将Dictionary类型转换为List类型的函数。 What will be the most efficient way to do this? 什么是最有效的方法?

For example... 例如...

Suppose this is my sample json string - 假设这是我的示例json字符串-

"{\"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();
        }
    }
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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