我一直在使用protobuf.js (命令行工具)、pbjs和pbts为我定义的.proto文件生成js和typescript类。我从我的后端API得到了一个json响应,我希望将其反序列化到protobuf生成的类中。推荐的方法是使用fromObject方法,该方法接受json对象。比方说我有
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实现这一点?
发布于 2020-09-09 09:07:34
我不认为你可以。包装器是消息,我认为protobuf.js没有为您拆箱这些值的选项。
但是ts-proto做到了!对于google.protobuf.StringValue code,它将创建一个属性签名code: string | undefined。听起来这就是你想要的。
但看起来“可选”的标签又回到了proto3。这意味着你可以这样写:
message ChangeEvent {
string source = 1;
optional string code = 2;
}这仍然是一个实验特性,在protoc v3.12.0中添加。而且你需要一个支持它的typescript插件。
其中就有一个:protobuf-ts。它将生成以下typescript:
interface ChangeEvent {
source: string;
code?: string
}免责声明:我是protobuf-ts的作者。
https://stackoverflow.com/questions/62704089
复制相似问题