[.NET Core] .NET Core 改用 Newtonsoft.Json

自從 .NET Core 3.0 開始,官方就已經將 System.Text.Json 作為專案預設的 JSON Library,不過我偶然在某次需求遇到特殊格式,System.Text.Json 不支援,需要將內建的 JSON 處理器替換成 Newtonsoft.Json,這裡展示一下設置的步驟。

 

有興趣的小夥伴可以看一下微軟官方的 System.Text.Json 介紹文章:

Try the new System.Text.Json APIs - .NET Blog (microsoft.com)

2022-11-30 更新~!

如果不想要改用 Newtonsoft.Json 的夥伴,也可以參考下一篇文章照樣用 System.Text.Json,再自己添加特殊格式的轉換器喔 👍

[.NET Core] System.Text.Json 添加 Customize JsonConverter | K. C. - 點部落 (dotblogs.com.tw)

 

 

 

前情提要

我在某次需求遇到一個狀況,別人傳給我的 JSON 會以「2022/06/02 00:00:00」這種 DateTime 格式,但是一傳就會拋出下列這種 error   ↓ 

The JSON value could not be converted to System.DateTime. Path: $.Data.StartDateTime | LineNumber: 3 | BytePositionInLine: 40.

 

爬文後發現,「MM/DD/YYYY」這種斜線的 DateTime 格式算是比較特殊的日期格式,很不幸的 System.Text.Json 無法轉換,後來得知  Newtonsoft.Json 可以支援這種格式,所以我打算將專案改使用 Newtonsoft.Json 

 

 

專案添加 Newtonsoft.Json 支援

安裝以下套件

Microsoft.AspNetCore.Mvc.NewtonsoftJson

 

Program.cs 添加 .AddNewtonsoftJson()

builder.Services.AddControllers().AddNewtonsoftJson();

 

 

PascalCase 設置

做好上述設置後,API 就已經可以接受「MM/DD/YYYY」的 DateTime 格式了。

不過如果之前有設置過 PascalCase 大寫開頭的命名格式,就會發現改成 Newtonsoft.Json 後設置失效了,postman 打 API 後回傳的 JSON 內容是 CamelCase 小寫開頭的

 

在 .NET Core 中, API Request Response 的 JSON 參數預設會幫你改成小寫開頭的駝峰式命名(CamelCase),在  System.Text.Json 會添加 .AddJsonOptions() 更改這種屬性  ↓  讓他不會再自動幫我們轉換,Model property 大寫開頭 json 就大寫。

JsonSerializerOptions.PropertyNamingPolicy 屬性 (System.Text.Json) | Microsoft Docs

 

 Newtonsoft.Json 就不能用 .AddJsonOptions() 更改了,要使用 Newtonsoft.Json 的設置方式才行

添加設置SerializerSettings

builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

 

 

Swagger 改用 Newtonsoft.Json

做完上述設置後,專案就已經支援 Newtonsoft.Json 輸出,並可輸出 PascalCase 的 JSON 了,但是打開 Swagger 會發現 PascalCase 的設置並沒有在 Swagger UI 中生效

 

這是因為雖然專案內的 JSON 處理已經改為 Newtonsoft.Json,但是 Swagger 還在使用 System.Text.Json,要把 Swagger 也改支援 Newtonsoft.Json 才行

 

安裝以下套件

Swashbuckle.AspNetCore.Newtonsoft

 

Program.cs 添加 .AddSwaggerGenNewtonsoftSupport()

builder.Services.AddSwaggerGenNewtonsoftSupport();

 

重 run 之後就正常了~

 

 

 

更多詳細說明可參考官方文章 在 ASP.NET Core Web API 中格式化回應資料 | Microsoft Docs