Reputation: 141
When you convert a Protobuf Message in Ruby to JSON using to_json
it converts all fieldnames to camelCase.
e.g. with protobuf message Person as
message Person {
string name = 1;
int32 id = 2;
string email_address = 3;
and Person in Ruby as
person = Person.new(:name => "Bob",
:id => 1,
:email_address => "[email protected]")
Serialized to JSON
person.to_json
>>> {"name":"Bob","id":"1","emailAddress":"[email protected]"}
the field email_address
gets serialized in camelCase instead of snake case as it is in the proto
How can you serialize it with the original proto fieldnames?
I tried converting it to a Ruby Hash
(with .to_h
) at first since it preserves field names, but ran into a different issue. Fields with double
values will be rendered as a Hash
like price: {"value": 10.0"}
instead of price: 10.0
.
Upvotes: 1
Views: 1767
Reputation: 141
Buried deep in the source code is the answer.
There is an option in to_json
to preserve the case used in the proto by passing in preserve_proto_fieldnames: true
e.g. person.to_json({preserve_proto_fieldnames: true})
Unfortunately this doesn't seem to be elsewhere in the Ruby protobuf documentation
Upvotes: 3