netcore 3+中,JsonProperty特性失效,使用JsonProperty重命名字段名稱


在我們之前常用的JsonProperty特性中,突然不再生效。查閱相關資料后發下:

之前版本中,netocre默認使用Newtonsoft.Json作為Json解析器,在3.0不再是默認,而是使用System.Text.Json替換Newtonsoft.Json

參考文章
官方文檔

如繼續使用Newtonsoft.Json作為Json解析器,

  1. 安裝Nuget
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Install-Package Newtonsoft.Json
  1. 注冊服務
services.AddControllers().AddNewtonsoftJson();
  1. 使用JsonProperty重命名字段名稱
public class WeatherForecast {

    // [JsonPropertyName("date123456")] 使用System.Text.Json 請看參考文章
    public DateTime Date { get; set; }

    [JsonProperty("TempC")]
    public int TemperatureC { get; set; }

    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

    public string? Summary { get; set; }
} 

但是這個地方有個問題,Newtonsoft.Json 在常規Controllers中寫是可以正常如上使用的,但是在.NET6的Mini API中不起作用

app.MapGet("/", () => {
    string [] _summaries = new []
      {"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};
    return Enumerable.Range(1, 5)
        .Select(index => new WeatherForecast {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = _summaries [Random.Shared.Next(_summaries.Length)]
        }).ToArray();
});

例如如上代碼無法將字段 TemperatureC =》 TempC 返回,System.Text.Json是可以的
哪位有Newtonsoft.Json的解決辦法,麻煩@一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM