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