簡體   English   中英

GRPC 消息將不遵守“json_name”選項 C#

[英]GRPC messages will not respect "json_name" option C#

We are currently using GRPC to send data from our database interface to our ASP.NET REST API to serve to the client (think of GRPC as the middleman between the database and REST API) and are having some issues preserving snake case for the field names of the轉換為 JSON 時的消息。

本質上,在根據語言指南創建 JSON 時,默認情況下 GRPC 將 map 消息中的字段名稱發送到 lowerCamelCase( my_field_name將是 JSON 中的myFieldName )。 但是,語言指南還指定如果您提供[json_name="my_field_name"]作為選項,那么它將使用該選項而不是 lowerCamelCase 版本。

這就是我們的問題發生的地方,當我們在字段上使用json_name時,它似乎根本不起作用。 我們正在使用 grpc.tools NuGet package 所以也許我們在那里遺漏了什么? 這是問題的一個例子:

.proto 文件會有這樣的消息:

message TestMessage {
    string my_field_name = 1 [json_name="my_field_name"];
}

然后我們在 JSON 中的 output 最終看起來像這樣,盡管使用了json_name

{
    "myFieldName": "blah"
}

需要考慮的一些注意事項:

  1. Our protos are contained in a seperate NuGet package that is being used by the ASP.NET REST API. NuGet package 在 .csproj 文件中包含以下內容:
<ItemGroup>
  <Content Include="**\*.proto" Pack="true" PackagePath="content" />
</ItemGroup>
  1. In the ASP.NET REST API we have the following in our.csproj file (Proto.Common is the NuGet package containing our proto files):
<ItemGroup>
  <PackageReference Include="Grpc.Tools" Version="2.48.1">
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
  <PackageReference Include="Proto.Common" Version="1.3.2" GeneratePathProperty="true" />
</ItemGroup>
<ItemGroup>
  <Protobuf Include="$(PkgProto_Common)\content\**\*.proto" ProtoRoot="$(PkgProto_Common)\content" GrpcServices="Both" />
</ItemGroup>

我們發現了這個 StackOverflow 響應,但不幸的是它似乎對我們沒有多大幫助。

這是一個預先存在的 API,因此將所有內容切換到 lowerCamelCase 並不理想。 任何幫助是極大的贊賞!

好吧,經過一番深入研究,我們終於找到了解決問題的方法。 事實證明,問題不是源於 GRPC,而是源於默認的 ASP JSON 序列化程序。

默認情況下,序列化程序會將變量名序列化為 camelCase,因此為了滿足我們的需要,我們必須將其配置為使用如下所示的 snake_case 命名策略來序列化名稱。

builder.Services.AddMvc().AddNewtonsoftJson(o =>
  o.SerializerSettings.ContractResolver = new DefaultContractResolver {
    NamingStrategy = new SnakeCaseNamingStrategy()
  }
);

希望這可以幫助遇到同樣問題的其他人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM