簡體   English   中英

將復雜的Json中的字典轉換為列表<string>

[英]Converting dictionary in a complex Json to list<string>

我有一個既包含字典又包含列表的JSON字符串。為了進行解析,存在一個將列表類型從JSON字符串轉換為字典的函數。 我需要編寫一個將Dictionary類型轉換為List類型的函數。 什么是最有效的方法?

例如...

假設這是我的示例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\"}"

這是從此處獲取字典值並將其轉換為字符串列表的有效方法。

    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