Google Protobuf - 在 Typescript 中从 JSON 反序列化

Dop*_*Dop 4 json protocol-buffers node.js typescript

我在 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;

Run Code Online (Sandbox Code Playgroud)

我发现一个引用此问题的问题:toObject -> Protobuf

小智 5

不幸的是,官方的 JavaScript 实现不支持 JSON。

您可以在一致性测试中看到它:https://github.com/protocolbuffers/protobuf/blob/0110ff565951ea52af37d6f155197048c378abe3/conformance/conformance_nodejs.js#L76

此行跳过 JSON 格式的所有测试,因为它尚未实现。

但 TypeScript 中还有替代的 protobuf 实现。比如protobuf-ts(这是一个不要脸的插件,我是作者)。它支持规范 proto3 JSON 格式的所有功能。它通过了所有一致性测试。而且它的占用空间比 google-protobuf ~40kb 和 ~400kb小得多。