Home > Mobile >  GRPC messages will not respect "json_name" option C#
GRPC messages will not respect "json_name" option C#

Time:09-15

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 message when converted to JSON.

Essentially, GRPC by default will map the field name in a message to lowerCamelCase when creating JSON as per the language guide (my_field_name would be myFieldName in JSON). However, the language guide also specifies that if you provide [json_name="my_field_name"] as an option then it would use that and not the lowerCamelCase version.

This is where our issue occurs, when we use json_name on a field it doesn't seem to work at all. We are using the grpc.tools NuGet package so maybe we are missing something there? Here is an example of the problem:

The .proto file would have a message like this:

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

And then our output in JSON ends up looking like this despite the use of json_name:

{
    "myFieldName": "blah"
}

Some notes to consider:

  1. Our protos are contained in a seperate NuGet package that is being used by the ASP.NET REST API. The NuGet package contains this in the .csproj file:
<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>

We found this StackOverflow response but unfortunately it didn't seem to help us much.

This is a preexisting API so switching everything over to lowerCamelCase would not be ideal. Any help is greatly appreciated!

CodePudding user response:

Alright, so after some deep diving we finally found a solution to the problem. Turns out that the issue wasn't stemming from GRPC but rather with the default ASP JSON serializer.

By default the serializer will serialize variable names to camelCase, so to fit our needs we had to configure it to serialize the names using the snake_case naming strategy as seen below.

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

Hope this might help someone else who bumps into the same problem!

  • Related