.NET JSON序列化/反序列化框架Newtonsoft.Json使用示例

在NuGet安装Newtonsoft.Json,引用后就可以在项目中使用了:



using Newtonsoft.Json;
using System;

namespace ConsoleApp1
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Created { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            User user = new User();
            user.Id = 1;
            user.Name = "dnawo";
            user.Created = DateTime.Now;

            //序列化
            Console.WriteLine("序列化:");
            string json = JsonConvert.SerializeObject(user);
            Console.WriteLine(json);
            //反序列化
            Console.WriteLine("反序列化:");
            User user1 = JsonConvert.DeserializeObject<User>(json);
            Console.WriteLine(user1.Name);

            Console.ReadLine();
        }
    }
}

运行结果:

引用内容 引用内容
序列化:
{"Id":1,"Name":"dnawo","Created":"2022-12-19T18:22:46.5993078+08:00"}
反序列化:
dnawo

使用JsonIgnore指定某些类成员不序列化

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    [JsonIgnore]
    public DateTime Created { get; set; }
}

引用内容 引用内容
{"Id":1,"Name":"dnawo"}

使用JsonProperty缩写类成员名称

public class User
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("na")]
    public string Name { get; set; }
    [JsonProperty("dt")]
    public DateTime Created { get; set; }
}

引用内容 引用内容
{"id":1,"na":"dnawo","dt":"2022-12-19T18:22:46.5993078+08:00"}

相关链接

[1].Newtonsoft.Json官网:https://www.newtonsoft.com/json

评论: 0 | 引用: 0 | 查看次数: 747
发表评论
登录后再发表评论!