我在 Google Protobuf 中有一些使用 Typecript 的对象,然后我将其序列化为 JSON 以持久保存到 AWS s3,因为我需要以这种格式使用 then。
但我的要求之一是反序列化(从包含 objInstance.toObject() 生成的 JSON 的字符串)。
有什么方法可以使用为其生成的代码吗?所有内部类(jspb.Message)不包含任何与反序列化相关的方法,除了 deserializeBinary,这不是我需要的。
关于 Node/Typescript 中 google protobuf 的文档目前非常差,甚至查看了存储库中的测试 ( https://github.com/protocolbuffers/protobuf/tree/master/js )
以下是生成代码中的函数:
serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): SearchResponse.AsObject;
static toObject(includeInstance: boolean, msg: SearchResponse): SearchResponse.AsObject;
static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
static serializeBinaryToWriter(message: SearchResponse, writer: jspb.BinaryWriter): void;
static deserializeBinary(bytes: Uint8Array): SearchResponse;
static deserializeBinaryFromReader(message: SearchResponse, reader: jspb.BinaryReader): SearchResponse;
我发现一个引用此问题的问题:toObject -> Protobuf
最佳答案
不幸的是,官方的 JavaScript 实现不支持 JSON。
此行跳过 JSON 格式的所有测试,因为它尚未实现。
但是 TypeScript 中有替代的 protobuf 实现。例如,protobuf-ts (这是一个无耻的插件,我是作者)。它支持all features规范的 proto3 JSON 格式。它通过了所有一致性测试。而且它的占用空间比 google-protobuf ~40kb vs ~400kb 小得多.
关于node.js - Google Protobuf - 在 Typescript 中从 JSON 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59579926/