C#的Json序列化
in C# with 0 comment

使用自带的Json库 System.Text.Json

一般使用

注意 要使用属性的方式去定义json的里面的内容 { get; set; }
using System.Text.Json;

class Progran
{
    class Person
    {
        public string Name { get; set; } = null!;
        public int Age { get; set; }
        public DateTime Birthday { get; set; }
    }

    public static void Main()
    {
        // 序列化
        List<Person> Persons =
        [
            new()
            {
                Name = "小明",
                Age = 18,
                Birthday = new DateTime(2000, 1, 1),
            },

            new()
            {
                Name = "小大",
                Age = 180,
                Birthday = new DateTime(2100, 1, 1),
            },
            new()
            {
                Name = "小小",
                Age = 1800,
                Birthday = new DateTime(2200, 1, 1),
            },
        ];

        string jsonString = JsonSerializer.Serialize(Persons);
        Console.WriteLine($"序列化\n{jsonString}\n");

        // 反序列化 返回的类型可能为空
        List<Person>? JsonToPersons = JsonSerializer.Deserialize<List<Person>>(jsonString);
        // 打一个断点 看一下 JsonToPersons 的值

    }
}

设置命名策略

对于一些需要单独设定的属性名称不一致的可以给属性加上特性 [JsonPropertyName(name: "要生成Json的名称")]
具体使用
如何使用 System.Text.Json 自定义属性名称和值

AOT生成

System.Text.Json 中的源生成在 .NET 6 及更高版本中提供。 在应用中使用时,应用的语言版本必须为 C# 9.0 或更高版本。
需要额外定义一个类 用特性 [JsonSerializable(typeof(需要处理的Json类型))] 一个类可以用多个特性修饰

using System.Text.Json;
using System.Text.Json.Serialization;

[JsonSerializable(typeof(Person))]
[JsonSerializable(typeof(List<Person>))]
public partial class JsonSourceContext : JsonSerializerContext { }

public class Person
{
    public string Name { get; set; } = null!;
    public string xx = null!;
    public int Age { get; set; }

    [JsonPropertyName(name: "Aaa")]
    public DateTime Birthday { get; set; }
}

class Progran
{
    public static void Main()
    {
        // 序列化
        List<Person> Persons =
        [
            new()
            {
                Name = "小明",
                Age = 18,
                xx = "SS",
                Birthday = new DateTime(2000, 1, 1),
            },
            new()
            {
                Name = "小大",
                Age = 180,
                Birthday = new DateTime(2100, 1, 1),
            },
            new()
            {
                Name = "小小",
                Age = 1800,
                Birthday = new DateTime(2200, 1, 1),
            },
        ];
        // 第一种也可以
        //string jsonString = JsonSerializer.Serialize(Persons, JsonSourceContext.Default.ListPerson);
        string jsonString = JsonSerializer.Serialize(Persons, typeof(List<Person>), JsonSourceContext.Default);
        Console.WriteLine($"序列化\n{jsonString}\n");

        // 反序列化 返回的类型可能为空
        List<Person>? JsonToPersons = JsonSerializer.Deserialize(jsonString, JsonSourceContext.Default.ListPerson);
        //打一个断点 看一下 JsonToPersons 的值
    }
}

如何在 System.Text.Json 中使用源生成

多态Json序列化

对于一些时候 里面的类型是多个不同的子类 比如 这样

public abstract class Shap
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Circle : Shap
{
    public int Radius { get; set; }
}

public class Rectangle : Shap
{
    public int Width { get; set; }
    public int Height { get; set; }
}

序列化的时候 如果是用Shap当作类型 那么圆形会丢失半径 矩形会丢失宽高
需要做的是在父类上面写上特性 实现不同的类型的不同处理方式

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

[JsonDerivedType(typeof(Circle), "circle")]
[JsonDerivedType(typeof(Rectangle), "rectangle")]
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
public abstract class Shap
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Circle : Shap
{
    public int Radius { get; set; }
}

public class Rectangle : Shap
{
    public int Width { get; set; }
    public int Height { get; set; }
}

class Progran
{
    public static void Main()
    {
        List<Shap> shapList =
        [
            new Rectangle
            {
                X = 10,
                Y = 11,
                Height = 12,
                Width = 12,
            },
            new Circle
            {
                X = 20,
                Y = 50,
                Radius = 50,
            },
        ];
        // 序列化
        string jsonString = JsonSerializer.Serialize(shapList);
        Console.WriteLine(jsonString);
        // 反序列化
        List<Shap>? JsonToPersons = JsonSerializer.Deserialize<List<Shap>>(jsonString);
    }
}

多态Json序列化 AOT

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

[JsonDerivedType(typeof(Circle), "circle")]
[JsonDerivedType(typeof(Rectangle), "rectangle")]
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
public abstract class Shap
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Circle : Shap
{
    public int Radius { get; set; }
}

public class Rectangle : Shap
{
    public int Width { get; set; }
    public int Height { get; set; }
}

[JsonSerializable(typeof(List<Shap>))]
public partial class JsonSourceContext : JsonSerializerContext { }

class Progran
{
    public static void Main()
    {
        List<Shap> shapList =
        [
            new Rectangle
            {
                X = 10,
                Y = 11,
                Height = 12,
                Width = 12,
            },
            new Circle
            {
                X = 20,
                Y = 50,
                Radius = 50,
            },
        ];
        // 序列化
        string jsonString = JsonSerializer.Serialize(shapList, JsonSourceContext.Default.ListShap);
        Console.WriteLine(jsonString);
        // 反序列化
        List<Shap>? JsonToPersons = JsonSerializer.Deserialize(
            jsonString,
            JsonSourceContext.Default.ListShap
        );
    }
}