zoukankan      html  css  js  c++  java
  • 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的解决办法,麻烦@一下

  • 相关阅读:
    SVN使用之分支、合并
    eq相等 ,ne、neq不相等 EL表达式
    PLSQL:plsql中文乱码,显示问号
    mysql中实现行号,oracle中的rowid
    安装完QQ必须要删除掉的几个恐怖文件
    关于table的一些兼容性问题
    Javascript事件绑定的几种方式
    jQuery中的一些正则匹配表达式
    将java类的泛型集合转换成json对象
    python登录豆瓣,发帖
  • 原文地址:https://www.cnblogs.com/shenghuotaiai/p/15717518.html
Copyright © 2011-2022 走看看