当前位置:   article > 正文

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

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

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

builder.Services.AddControllers().AddJsonOptions((opt) =>
{
    opt.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
    opt.JsonSerializerOptions.WriteIndented = true;
});
  • 1
  • 2
  • 3
  • 4
  • 5

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
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/620334
推荐阅读
相关标签
  

闽ICP备14008679号