json.net 字典json字串相互轉換
阿新 • • 發佈:2021-08-10
參考官方連線:
Deserialize a Dictionary (newtonsoft.com)
步驟1:vs 專案安裝對應包
步驟2: 新增using 引用using Newtonsoft.Json;
完整程式
程式程式碼:
1 using System; 2 using System.Collections.Generic; 3 using Newtonsoft.Json; 4 5 namespace ConsoleApp5 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 /* 字典序列化到json字串 */ 12 //建立字典物件 13 Dictionary<string, int> points = new Dictionary<string, int> 14 { 15 { "James", 9001 }, 16 { "Jo", 3474 }, 17 { "Jess", 11926 } 18 };19 //將字典物件轉換為 json字串 20 string json = JsonConvert.SerializeObject(points, Formatting.Indented); 21 //終端列印顯示 22 Console.WriteLine("字典轉json串-->" + json); 23 24 /* json 字串轉換到字典物件 */ 25 Dictionary<string, int> read = JsonConvert.DeserializeObject<Dictionary<string, int>>(json); 26 //列印字典指定KEY值 27 Console.WriteLine("json轉字典-->James: " + read["James"]); 28 29 //等待按鍵輸入,使得中斷視窗懸停 30 Console.ReadKey(); 31 } 32 } 33 }
終端列印輸出: