Try   HackMD

.NET Core 3.1 Json 屬性調整


1.物件屬性的Attribute改變

NET Core 2.1 的物件Json轉換是透過 Newtonsoft.Json 進行物件的正反序列化動作

using Newtonsoft.Json;

    public class Student
    {
        [JsonProperty("studentName")]
        public string Name { get; set; }

        [JsonProperty("studentAge")]
        public int Age { get; set; }
    }

但是在 NET Core 3.1 正式發布版本 已經非支援 Newtonsoft.Json 而是微軟自己開發內建的 Text.Json.Serialization

using System.Text.Json.Serialization;

    public class Student
    {
        [JsonPropertyName("studentName")]
        public string Name { get; set; }

        [JsonPropertyName("studentAge")]
        public int Age { get; set; }
    }

其中在model 物件或屬性的Json格式部分已經從 JsonProperty() 調整成 JsonPropertyName()

2.序列化與反序列化的改變

NET Core 2.1 是物件與字串的正反序列化方式():

using Newtonsoft.Json;

string resultStr = JsonConvert.SerializeObject(student);
Student student = JsonConvert.DeserializeObject<Student>(resultStr);

NET Core 3.1 的改變是:

using System.Text.Json.Serialization;

string resultStr = JsonSerializer.Serialize(student);
Student student = JsonSerializer.Deserialize<Student>(resultStr);
tags: netcore modelvalidate WebAPI Json