在aspNetCore中 使用System.Text.Json的定制功能, 将定制化的json返回给前端

发布于:2024-05-20 ⋅ 阅读:(175) ⋅ 点赞:(0)

C# 默认大写, 而大部分的前端默认小写, 这时候可以如此配置:

builder.Services.AddControllers().AddJsonOptions((opt) =>
{
    opt.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
    opt.JsonSerializerOptions.WriteIndented = true;
});

JsonNamingPolicy 还有诸多配置方案. 下面介绍一些更加定制化的功能, 用控制台程序举例:

using JsonTest;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;


List<Teacher> teachers = new();
for (int i = 0; i < 5; i++)
{
    teachers.Add(new()
    {
        Id = i + 1,
        FullName = $"FullName{i}"
    });
}

Student student = new()
{
    Id = 1,
    FullName = "James",
    Description = "AAA",
    workDays = WorkDays.Monday| WorkDays.Tuesday,
    Teachers = teachers,
    Date = DateTime.Now
};

JsonSerializerOptions options = new()
{
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
var a = JsonSerializer.Serialize<Student>(student, options);


Console.WriteLine(a);


class Student
{
    //定制化, TableId的首字母不会应用CamelCase
    [JsonPropertyName("TableId")]
    public int Id { get; set; }

    public string FullName { get; set; } = string.Empty;

    /// <summary>
    /// 序列化时忽略
    /// </summary>
    [JsonIgnore]
    public string Description { get; set; } = string.Empty;

    public DateTime Date { get; set; }

    [JsonConverter(typeof(JsonStringEnumConverter))]
    public WorkDays workDays { get; set; }

    public List<Teacher> Teachers { get; set; } = new();
}

class Teacher
{
    public int Id { get; set; }
    public string FullName { get; set; } = string.Empty;
}

    [Flags]
    enum WorkDays
    {
        Monday = 1,
        Tuesday = 2,
        Wednesday = 4,
        Thursday = 8,
        Friday = 16,
        Saturday = 32,
        Sunday =64
    }

结果:
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到