在我們之前常用的JsonProperty特性中,突然不再生效。查閱相關資料后發下:
之前版本中,netocre默認使用Newtonsoft.Json作為Json解析器,在3.0不再是默認,而是使用System.Text.Json替換Newtonsoft.Json
如繼續使用Newtonsoft.Json作為Json解析器,
- 安裝Nuget
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Install-Package Newtonsoft.Json
- 注冊服務
services.AddControllers().AddNewtonsoftJson();
- 使用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的解決辦法,麻煩@一下