VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C# NewtonJson Serialize and deserialize

复制代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO; 
using System.Threading;
using Newtonsoft.Json;
using System.Text;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            DictionaryJsonDemo();
            Console.ReadLine();
        }

        static void DictionaryJsonDemo()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < 10; i++)
            {
                string key = Guid.NewGuid().ToString();
                dic.Add(key, key);
            }
           
            var serializedJson = JsonConvert.SerializeObject(dic,Formatting.Indented);
            Console.WriteLine("Serialized json:");
            Console.WriteLine(serializedJson);
            WriteContentToJson(serializedJson);
            Dictionary<string, string> deserializedDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(serializedJson);
            foreach(var d in deserializedDic)
            {
                Console.WriteLine($"Key:{d.Key},Value:{d.Value}");
            }
        }

        static void WriteContentToJson(string msg)
        {
            string jsonFile = @"..\..\..\Resource\JsonFile.json";
            using(StreamWriter msgWriter=new StreamWriter(jsonFile,false,Encoding.UTF8))
            {
                msgWriter.WriteLine(msg);
            }
        }
}
复制代码

Relative file path @"..\formerdirectory",@"..\..\AboveTwoDir",@"..\..\..\AboveThreeDir";


相关教程