.NET 对象转JSON时忽略值为null的字段

permission.json

public class Permission
{
    public Guid Id { get; set; }
    public Guid? Pid { get; set; }
    public Guid? Mid { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public string? Code { get; set; }
    public string? Icon { get; set; }
    public bool? Enabled { get; set; }
    public int? OrderSort { get; set; }
    public bool IsButton { get; set; }
    public bool IsHide { get; set; }
}
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;

string fContent = File.ReadAllText(Path.Combine(Environment.CurrentDirectory,"permissions.json"));
var ps = JsonSerializer.Deserialize>(fContent);

var desktopPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"permission.json");

var jsonOptions = new JsonSerializerOptions()
{
    WriteIndented = true,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
        Encoder = JavaScriptEncoder.Create(UnicodeRanges.All, UnicodeRanges.All)
};
var oContent = JsonSerializer.Serialize(ps,jsonOptions);
File.WriteAllText(desktopPath, oContent);

结果


image.png

你可能感兴趣的:(.NET 对象转JSON时忽略值为null的字段)