C#JSON序列反序列化(System.Text.Json)

145 阅读1分钟

建立一个复杂的类:

    internal enum Level
    {
        LEVELONE,
        LEVELTWO,
        LEVELTHREE,
    }

    internal class School
    {
        public Level level;
        public List<Grade> Grades { get; set; }

        public string SchoolName { get; set; }

        public int SchoolAge { get; set; }

        public Dictionary<string, int> GradePeopleNum { get; set; }
    }

    internal class Grade
    {
        public int ClassNum { get; set; }

        public string GradeName { get; set; }

        public List<Class> ClassList { get; set; }
    }

    internal class Class
    {
        public int Students { get; set; }
    }

初始化后.

1.序列化

进行优质输出需要 设置 WriteIndented = true 来“use pretty printing.”

    // 摘要:
    //     Provides options to be used with System.Text.Json.JsonSerializer.
    public sealed class JsonSerializerOptions
    {
      ...
           // 摘要:
        //     Gets or sets a value that indicates whether JSON should use pretty printing.
        //     By default, JSON is serialized without any extra white space.
        //
        // 返回结果:
        //     true if JSON is pretty printed on serialization; otherwise, false. The default
        //     is false.
        //
        // 异常:
        //   T:System.InvalidOperationException:
        //     This property was set after serialization or deserialization has occurred.
        public bool WriteIndented { get; set; }
			...
}

2.反序列化

反序列化

3.其他功能及需要注意的

 3.1 如图,发现这字段序列化后并没有显示,但是能成功反序列化。

字段序列化被隐藏

解决:在字段上加上特性[JsonInclude]。

显示序列化字段

3.2  加上[JsonPropertyName("Username")] 可以输出自己想要的名字

3.3 注意到枚举值序列化时是以整数形式输出

解决:加上[JsonConverter(typeof(JsonStringEnumConverter))]

序列化以枚举值名称输出

3.4 序列化顺序 [JsonPropertyOrder()]设置,默认为0,从小到大,相同时已在类中书写顺序排列。