Home >Backend Development >Golang >How Can I Customize Protobuf Extension Field Names in JSON Output?

How Can I Customize Protobuf Extension Field Names in JSON Output?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 15:17:13749browse

How Can I Customize Protobuf Extension Field Names in JSON Output?

Customizing Protobuf Extension Field Names in JSON

When extending a message in Protocol Buffers (protobuf) and marshalling it as JSON, the field name for the extended message typically appears in brackets with the prefix "message.extension_message_name." This can be inconvenient and confusing, especially if the extension message is used elsewhere in the API with a different name.

The issue stems from the logic in Protobuf's jsonpb library, where the JSON name is set as "[%s]" desc.Name, with desc.Name representing the unqualified extension field name.

To circumvent this limitation, the language guide suggests using the json_name field option to override the default JSON name. By adding json_name = "custom_name" to the extension field, the field will be serialized with the specified custom_name in JSON:

message TestMessage {
    extend TestMessage {
        ExtensionPlacement extension_message_name = 10;
        String messageField = 10 [json_name = "customFieldName"];
    }
}

With this modification, the extended field will appear as "customFieldName" in JSON, as desired.

The above is the detailed content of How Can I Customize Protobuf Extension Field Names in JSON Output?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn