NewtonsoftJson的[JsonIgnore] Attribute不起作用


使用Visual Studio 2019的ASP.NET Core Web Application模板(ASP.NET Core 3.1)創建Web Api項目,選擇控制台方式(即使用.Net Core自帶的Kestrel Web Server,而不是IIS Express)啟動運行項目,默認響應報文如下:

HTTP/1.1 200 OK
Connection: close
Date: Sun, 24 May 2020 14:14:18 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked

[
  {
    "date": "2020-05-25T22:14:18.347603+08:00",
    "temperatureC": 23,
    "temperatureF": 73,
    "summary": "Hot"
  },
  {
    "date": "2020-05-26T22:14:18.3476146+08:00",
    "temperatureC": -5,
    "temperatureF": 24,
    "summary": "Freezing"
  },
  {
    "date": "2020-05-27T22:14:18.3476154+08:00",
    "temperatureC": 53,
    "temperatureF": 127,
    "summary": "Chilly"
  },
  {
    "date": "2020-05-28T22:14:18.3476156+08:00",
    "temperatureC": -1,
    "temperatureF": 31,
    "summary": "Chilly"
  },
  {
    "date": "2020-05-29T22:14:18.3476158+08:00",
    "temperatureC": 10,
    "temperatureF": 49,
    "summary": "Bracing"
  }
]

 

現在我想響應實體不再返回temperatureF字段,依據官方文檔添加了常用的NewtonsoftJson包,並在相應字段加上[JsonIgnore] Attribute, 再次啟動項目,發現沒有起作用。

1     public void ConfigureServices(IServiceCollection services) 2  { 3  services.AddControllers().AddNewtonsoftJson(); 4     }

 

 1 using System;  2 using System.Text.Json.Serialization;  3 
 4 namespace WebApi  5 {  6   public class WeatherForecast  7  {  8     public DateTime Date { get; set; }  9 
10     public int TemperatureC { get; set; } 11 
12  [JsonIgnore] 13     public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 14 
15     public string Summary { get; set; } 16  } 17 }

 

仔細檢查發現WeatherForecast所引用的命名空間不正確,修改成using Newtonsoft.Json; 再次運行,達到了想要的效果。那么,用.NET core自帶的System.Text.Json能否達到同樣的效果呢?答案是肯定的。即創建完項目直接在TemperatureF添加[JsonIgnore] Attribute,並添加相應引用(using System.Text.Json.Serialization;)即可。

 

總結:.NET core自帶的System.Text.Json和Newtonsoft.Json有同名的Attribute,如上面所說的JsonIgnore,在使用Newtonsoft.Json的時候要注意引用正確的包。


免責聲明!

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



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