【问题标题】:ASP Web API: Specifying custom field name when serializing object to JSONASP Web API:将对象序列化为 JSON 时指定自定义字段名称
【发布时间】:2020-11-09 20:02:07
【问题描述】:

我的解决方案中有几个项目。以下是其中 2 个:

  • API(netcoreapp3.1 asp web API - 因此 System.Text.Json 可用)
  • 实体(netstandard2.0 类库 - 因此 System.Text.Json 在那里不可用)。

实体包含我的 API 的 DTO(数据传输对象)。我需要为 DTO 提供我自己的 JSON 字段名称。我遇到了这个question,所以我尝试使用由System.Text.Json(.net core 3)提供的JsonPropertyNameAttribute,但它不起作用。

我需要做什么来指定自定义 JSON 字段名称?将Entities项目类型改成netcoreapp3.1(那么其他.net标准2.0库有问题)?使用不同的方式为 DTO 指定自定义 JSON 字段名称(我不想使用 Newtonsoft.Json,因为我听说它与 .net core 3+ asp Web API 存在兼容性问题)?

更新:正如strickt01所指出的,有NuGet package为其他.net版本提供System.Text.Json序列化和反序列化,例如:

  • .NET Standard 2.0 及更高版本
  • .NET Framework 4.7.2 及更高版本
  • .NET Core 2.0、2.1 和 2.2

【问题讨论】:

  • 您可以将 DTO 映射到 API 项目中指定的另一个类,然后使用 JsonPropertyNameAttribute。
  • @JacobSobus,但我不想在我的 API 项目中有类似 DTO 的类。这就是我决定将 API 和实体放在两个独立项目中的原因。
  • @JacobSobus,在我的实体项目中,我有两种类型的实体。第一个是 EF Core 模型(与我的数据库结构相匹配)。第二种类型是在 API 端点内部使用的 DTO。他们不同。我需要一种方法将 JSON 序列化 DTO 的字段名称从“CreationDate”更改为“creation_date”。
  • 然后我会将 DTO 提取到其他项目中,供 API 和实体使用。将其作为 .net 核心项目并使用 JsonPropertyNameAttribute :) 恕我直言,这将是最好的选择 :)
  • @JacobSobus 感谢您的建议。我想我同意你的看法。

标签: c# json rest asp.net-core asp.net-web-api


【解决方案1】:

如果您不想使用 Newtonsoft.Json(setting it as the default serializer in your .net core 3 project),那么您确实遇到了您确定的第 22 个问题。但是,如果您的自定义名称都遵循相同的格式,那么您可以设置 custom naming policy for the System.Text.Json serializer。即

services.AddControllers()
.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = new PascalToUnderscoreNamingPolicy(),
});

...PascalToUnderscoreNamingPolicy 是一个覆盖 JsonNamingPolicy.ConvertName 的类,以便将“CreationDate”之类的转换为“creation_date”。

【讨论】:

  • 感谢您的回答,但我的自定义名称不一定与属性名称匹配
  • 当您说JsonPropertyNameAttribute“不起作用”时,您是什么意思 - 尽管已将属性应用于 DTO,但仍会被忽略?
  • 我的意思是 [JsonPropertyName] 属性由 System.Text.Json 提供(仅在 .net core 3 中可用),它不能在 .net 标准项目中使用(实体项目是 netstandard 2.0类库)
  • System.Text.Json 通过 nuget 包支持 .net 标准 2.0(请参阅 docs.microsoft.com/en-us/dotnet/standard/serialization/…
  • 谢谢。我不知道。
猜你喜欢
  • 2017-08-08
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2020-07-02
  • 2010-09-20
相关资源
最近更新 更多