如何将Ruby protobuf消息转换为JSON,同时保留原型中使用的情况?



当您使用to_json将Ruby中的Protobuf Message转换为JSON时,它将所有字段名转换为camelCase。

。使用protobuf message Person作为

message Person {
string name = 1;
int32 id = 2;
string email_address = 3;

和Person在Ruby中作为

person = Person.new(:name => "Bob",
:id => 1,
:email_address => "foo@bar.com")

序列化为JSON

person.to_json
>>> {"name":"Bob","id":"1","emailAddress":"foo@bar.com"}

字段email_address被序列化为camelCase而不是蛇形case,因为它在原型

中如何用原始的原型字段名序列化它?

我尝试将其转换为RubyHash(.to_h),因为它保留了字段名称,但遇到了不同的问题。具有double值的字段将呈现为Hash,如price: {"value": 10.0"}而不是price: 10.0

答案隐藏在源代码的深处。

to_json中有一个选项,通过传递preserve_proto_fieldnames: true

来保留原型中使用的情况。。person.to_json({preserve_proto_fieldnames: true})

不幸的是,这似乎没有在Ruby protobuf文档的其他地方

最新更新