木子屋 Dnawo's BLOG

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

👤 dnawo 📅 2022-12-19 👁 2267 👍 0 💬 0 🔄 本站原创
在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)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 jQuery.ajax向服务器端post提交json数据错误及… 下一篇 → ASP.NET(C#)接收POST提交的JSON数据示例