C# JSON学习之序列化与反序列化

在我的个人计划中,学习制作c#下的曲线平台属于下半年的重点。关于前后端的数据传递-json数据的学习很有必要,通过一个例子来加深自己的理解。

新建一个console控制台程序,通过导入NewstonSoft的dll来实现json的转换,具体用法如下:

1.导入:使用nuget包导入方式,在命令行中输入:install-package newtonsoft.json  进行安装。

2.使用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace JsonDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Person myself = new Person
            {
                ID = 123,
                Name = "Afzaal Ahmad Zeeshan",
                Gender = true,
                DateOfBirth = new DateTime(1995, 08, 29)
            };

            // 序列化这个对象.  
            string serializedJson = JsonConvert.SerializeObject(myself);

            // 将对象信息打印在命令行屏幕中  
            Console.WriteLine(serializedJson);
          

            string data = "{\"ID\": 123,\"Name\": \"Afzaal Ahmad Zeeshan\",\"Gender\":   true, \"DateOfBirth\": \"1995-08-29T00:00:00\"}";  
    // Serialize it.  
Person obj = JsonConvert.DeserializeObject < Person > (data);  
  
// Print on the screen.  
Console.WriteLine(obj.ID);
Console.ReadKey();
        }
    }
}

通过这个例子基本熟悉了关于Json数据的序列化(转换为json字符串)以及反序列化(转换为对象)操作。

参考:

从入门到精通 C# 的 JSON 处理

猜你喜欢

转载自blog.csdn.net/sheng1522098487/article/details/80762067