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

标签 node.js json typescript protocol-buffers

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

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

此行跳过 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/

相关文章:

php - 将 PHP 多维数组返回到 Javascript/AJAX

javascript - pie() 不接受对象数组

arrays - 如何知道我的数据库数组中存在哪个数组元素?

javascript - Nodejs 拼接 JSON 元素效果不佳

node.js openssl 错误 : dh key too small

c# - 使用 C# 解析复杂的 JSON

generics - 我可以使用 function.call() 调用通用函数吗?

html - 响应和自定义时间轴

javascript - promise 拒绝不触发

node.js - 来自 mongoose 回调的 Express js res.redirect() 不起作用