.NET 6 Text.Json範例

目的

不使用Newtonsoft.Json,改採.net6內建的System.Text.Json System.Text.Json更著重在效能與安全性,大多數人應該都跟我一樣只會使用基本的序列化及反序列化。

建立新專案

設定新的專案

其他資訊

編輯WeatherForecastController檔案

    /// <summary>
    /// 序列化
    /// </summary>
    /// <returns></returns>
    [HttpGet("JsonSerialize")]
    public ActionResult JsonSerialize() {
      var Test = new TestClass() {
        Name = "中文名",
        Age = 18
      };
      var Result = JsonSerializer.Serialize(Test);
      return Ok(Result);
    }
    /// <summary>
    /// 反序列化
    /// </summary>
    /// <returns></returns>
    [HttpGet("JsonDeserialize")]
    public ActionResult JsonDeserialize() {
      var jsonString = @"{""Name"":""中文名"",""Age"":18}";
      var Result = JsonSerializer.Deserialize<TestClass>(jsonString);
      return Ok(Result);
    }
    public class TestClass {
      public string Name { get; set; }
      public int Age { get; set; }
    }

執行結果

延伸問題

在不做任何設定的情況下,內建的序列化會有些微差異

  • 序列化預設會將所有非ASCII轉為Unicode代碼,例如:中文名=>\u4E2D\u6587\u540D

使用ActionResult中的JsonResult回傳時會將開頭改為小寫

  • 反序列化後輸出為小寫的key(如結果2),原先的TestClass是大寫的Name與Age

兩個問題都會在另一個章節補充說明

參考

Compare Newtonsoft.Json to System.Text.Json, and migrate to System.Text.Json

範例檔

GitHub

Last updated