# 用 C# 將 JSON 字串轉換為 Dictionary 物件 & 樹狀圖格式(JsonConvert.SerializeObject) ###### tags: `ASP.NET` `C#` `JSON` ## 目的 用 C# 將 JSON 字串轉換成容易閱讀的樹狀圖格式。 ## 技術 1. C# 的 JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented); 2. C# 可以將 JSON 字串轉換為 Dictionary<string, object> 物件,再轉換回 JSON 字串。 ## 範例 ``` C# using Newtonsoft.Json; using System; using System.Collections.Generic; namespace ConsoleApp1 { class Program { internal class Product { public string[] Sizes { get; set; } public decimal Price { get; set; } public DateTime Expiry { get; set; } public string Name { get; set; } } static void Main(string[] args) { Product product = new Product { Name = "Apple", Expiry = new DateTime(2008, 12, 28), Price = 3.99M, Sizes = new[] { "Small", "Medium", "Large" } }; // 1. 把物件轉換為 JSON 字串 : string jsonStr = JsonConvert.SerializeObject(product); Console.WriteLine("1. 把物件轉換成 JSON 字串 : "); Console.WriteLine(string.Empty); Console.WriteLine(jsonStr); // 2. 把物件轉換為 JSON 字串,並設定縮排 : string jsonStrFormat = JsonConvert.SerializeObject(product, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(string.Empty); Console.WriteLine("2. 把物件轉換成 JSON 字串,並設定縮排 : "); Console.WriteLine(string.Empty); Console.WriteLine(jsonStrFormat); // 3. 把 JSON 字串轉換為 Dictionary<string, object> 物件,再轉換回 JSON 字串、並設定縮排 : Dictionary<string, object> strObjDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonStr); string jsonStrFromDic = JsonConvert.SerializeObject(strObjDic, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(string.Empty); Console.WriteLine("3. 把 JSON 字串轉換成 Dictionary<string, object> 物件,再轉換回 JSON 字串、並設定縮排 : "); Console.WriteLine(string.Empty); Console.WriteLine(jsonStrFromDic); // 4. 把 JSON 字串轉換回物件 : Product deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonStr); Console.ReadLine(); } } } ``` ## 範例結果 ![](https://i.imgur.com/GYAHuam.png) ## 用 C# 將 JSON 字串轉換為Dictionary<string, object>物件 * Dictionary 的 Key 會是原本物件的屬性名稱,Value 則是屬性的 Value: ![](https://i.imgur.com/6GX0rI4.png) ## 參考資料 * How do I get formatted JSON in .NET using C#? https://stackoverflow.com/questions/2661063/how-do-i-get-formatted-json-in-net-using-c