node protobuf 反序列化自动转驼峰命名?
发布于 6 年前 作者 samkeke 7054 次浏览 来自 问答

我使用的是https://github.com/dcodeIO/ProtoBuf.js 中的6.6.3的版本,nodejs版本是V8.9.0,使用protobuf过程中反序列化的时候字段名称自动转成驼峰命名,eg:show_time转成了showTime,我看了proto语法,上面说默认反序列化字段名称会使用驼峰命名,请问我想使用下划线命名怎么设置呢? 下面附上图片 t.js文件 QQ截图20180123110536.png proto文件 schema.proto QQ截图20180123110547.png 问题图片 QQ截图20180123110724.png

18 回复

自己顶一下,在线等

对的,注意看文档,_ 自动转驼峰

哪位大神帮忙解决一下

@imhered 嗯,我看了proto的语法,它是使用的驼峰命名,但是这样已经改变了我的字段名称了,我想用原来的以下划线命名

@imhered 难道这是硬性条件吗?

@samkeke 你非要用下划线的话 ,实在不行写个函数转一下吧

@imhered 是啊,必须使用下划线

@imhered 写函数,我得看一遍protobufjs的源码,这样不太实际,不知道他们有没有提供这样的方法

@imhered 因为这个是接口对接到外面,我给他们返回buffer,他们自己就转了,不可能说让人家重新定义字段名称

我看JAVA的字段名称可以使用下划线命名,不知道为什么node就不可以,好坑啊

@samkeke 试试别的npm包看看是不是这样,因为我也只用过你文中的这包

@imhered 嗯,好的,谢谢了,我再看看有没有其他方法能解决的

Proto sources only:

  --keep-case      Keeps field casing instead of converting to camel case.

@atian25 得改下配置吗?请问从哪里更改呢?

@atian25 我在最新版看到他们封装好的方法了,我试了下是可以使用的,但是不知道怎么引入proto文件

// this example demonstrates a way to keep field casing (as defined within .proto files) // while still having virtual getters and setters for the camel cased counterparts.

/eslint-disable strict, no-console/ var protobuf = require("…");

var proto = “syntax=“proto3”;
message MyMessage {
string some_field = 1;
}”;

var root = protobuf.parse(proto, { keepCase: true }).root; // or use Root#load

// converts a string from underscore notation to camel case function toCamelCase(str) { return str.substring(0,1) + str.substring(1).replace(/_([a-z])(?=[a-z]|$)/g, function($0, $1) { return $1.toUpperCase(); }); }

// adds a virtual alias property function addAliasProperty(type, name, aliasName) { if (aliasName !== name) Object.defineProperty(type.ctor.prototype, aliasName, { get: function() { return this[name]; }, set: function(value) { this[name] = value; } }); }

// this function adds alternative getters and setters for the camel cased counterparts // to the runtime message’s prototype (i.e. without having to register a custom class): function addVirtualCamelcaseFields(type) { type.fieldsArray.forEach(function(field) { addAliasProperty(type, field.name, toCamelCase(field.name)); }); type.oneofsArray.forEach(function(oneof) { addAliasProperty(type, oneof.name, toCamelCase(oneof.name)); }); return type; }

var MyMessage = addVirtualCamelcaseFields(root.lookup(“MyMessage”));

var myMessage = MyMessage.create({ some_field /* or someField */: “hello world” });

console.log( “someField:”, myMessage.someField, "\nsome_field:", myMessage.some_field, "\nJSON:", JSON.stringify(myMessage) );

@atian25 用的 var root = protobuf.parse(proto, { keepCase: true }).root; // or use Root#load 这个,在官网看到的说用这个APi就可以按照之前定义的字段名称来,不会自动转驼峰了,{ keepCase: true } ,,,现在问题是proto文件怎么引入进去

@samkeke 做法在这里: const root = new pb.Root(); // keepCase:保持默认的case 状态,pb自动会将test_demo 转换成 testDemo root.load(filepath, { keepCase: true }).then(pbroot => { resolve(root); }, err => { reject(err); });

回到顶部