• 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的解决办法,麻烦@一下

  • 相关阅读:
    cron生成
    sp_addlinkedserver,Synonym
    上海城市坐标
    评分插件 jquery.raty.js
    ORA-12514: TNS:listener does not currently know of service requested in connect
    ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist
    工厂模式
    单例模式
    Qt中的Q_OBJECT作用, 以及信号槽
    DDLog-不同颜色打印信息
  • 原文地址:https://www.cnblogs.com/shenghuotaiai/p/15717518.html
Copyright © 2020-2023  润新知