Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying the JSON name for protobuf extension

I've added an extending message to a message and need to marshal it as a json. However the field name for the extension message is [message.extension_message_name].

I would prefer it to be named just extension_message_name, without the braces and prefix, since this extension message exists elsewhere in our API and and having this weird name adds confusion.

As far as I can tell the bit of code responsible is in protobuf/jsonpb, where the JSONName is set with fmt.Sprintf("[%s]", desc.Name and cannot be overwritten it seems.

Anyone have a workaround for this?

like image 643
MffnMn Avatar asked Nov 04 '16 17:11

MffnMn


People also ask

Does protobuf use JSON?

JSON is mostly used in web applications where data exchange takes place between a browser and the server. Protobuf supports more data types than JSON. JSON is limited to certain python objects, and it cannot serialize every python object. Protobuf supports a wider range of data types when compared to JSON.

What is protobuf extension?

Extension (protobuf v0. 11.0) Extensions let you set extra fields for previously defined messages(even for messages in other packages) without changing the original message.

What is the protobuf file format?

Protocol Buffers (Protobuf) is a free and open-source cross-platform data format used to serialize structured data. It is useful in developing programs to communicate with each other over a network or for storing data.


1 Answers

As per the language guide:

Message field names are mapped to lowerCamelCase and become JSON object keys. If the json_name field option is specified, the specified value will be used as the key instead.

So tagging your field with json_name should do the trick, for example this:

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

Should make myField have the name my_special_field_name when marshalled to JSON.

like image 163
abcalphabet Avatar answered Oct 20 '22 22:10

abcalphabet