Skip to content

Support for "UseProtoEnumValueNames" option #56

Description

@Havret

Feature description

When using the Protobuf.System.Text.Json class to serialize protobuf messages with enum fields, the resulting JSON output does not match the original proto enum value. Instead of using the proto enum value name, the property is being serialized using default System.Text.Json. The same holds for the deserialization. We should add an option to change the way how the enums are serialized/deserialized so it's possible to handle payload that have been serialized using default protobuf to json serialization.

Feature in action

syntax = "proto3";

package MyPackage;

enum TestEnum {
  UNKNOWN = 0;
  FIRST_OPTION = 1;
  SECOND_OPTION = 2;
}

message MyMessage {
  TestEnum enum_field = 1;
}
var msg = new MessageWithEnum
{
    EnumField = TestEnum.FirstOption
};

var jsonSerializerOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
jsonSerializerOptions.AddProtobufSupport(options =>
{
    options.UseProtoEnumValueNames = true;
});

var serialized = JsonSerializer.Serialize(msg, jsonSerializerOptions);
{
  "enumField": "FIRST_OPTION"
}

Describe alternatives you've considered

Create custom converters for each enum type in the protobuf contract: This approach requires additional development and maintenance efforts for each enum type and is not a generic solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions