Home >Backend Development >Golang >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!