我一直在使用 protobuf.js(命令行工具)pbjs 和 pbts 为我定义的 .proto 文件生成我的 js 和 typescript 类。我从我的后端 API 收到一个 json 响应,我希望将其反序列化为 protobuf 生成的类。推荐的方法是使用接受 json 对象的 fromObject 方法。假设我有
message ChangeEvent {
string source = 1;
google.protobuf.StringValue code = 2;
}
我希望能够通过:
const changeEventWithCode = {
source = 'test',
code = 'code',
}
const changeEventWithoutCode = {
source = 'test',
code = null,
}
并让它们都编码和解码为同一事物。但是,如果我想设置代码字符串,我必须这样做:
const changeEventWithCode = {
source = 'test',
code = {
value: 'code',
},
}
我希望 fromObject 可以处理这个问题,但它没有 - 有什么方法可以挂钩一些定制来做到这一点。或者,如何使用 typescript 使用 protobufjs 来实现这一点?