Skip to content

Json序列化

介绍

框架内置了强类型IDStronglyTypedId、RowVersion、UpdateTime等类型来辅助建模,为了使这些类型在Json序列化更好地支持,框架提供了JsonConverter来支持这些类型的序列化。

同时支持了Newtonsoft.Json和System.Text.Json两种Json序列化库。

如何使用

System.Text.Json

在Program.cs中添加如下代码:

builder.Services.AddMvc()
  .AddNetCorePalSystemTextJson();

Newtonsoft.Json

在Program.cs中添加如下代码:

builder.Services.AddMvc()
  .AddNetCorePalNewtonsoftJson();

备注: Newtonsoft.Json的支持需要引用NetCorePal.Extensions.NewtonsoftJson包。

其它场景

如果需要在其它场景中使用,可以直接使用AddNetCorePalJsonConverters扩展方法添加EntityIdJsonConverterFactory、RowVersionJsonConverter、UpdateTimeJsonConverter等Converter。

System.Text.Json

using System.Text.Json;

var options = new JsonSerializerOptions();
options.AddNetCorePalJsonConverters();

Newtonsoft.Json

using Newtonsoft.Json;

var settings = new JsonSerializerSettings();
settings.AddNetCorePalJsonConverters();