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";

 

posted @ 2020-02-25 10:02  FredGrit  阅读(485)  评论(0编辑  收藏  举报