【问题标题】:Google Protobuf - Deserialize from JSON in TypescriptGoogle Protobuf - 在 Typescript 中反序列化 JSON
【发布时间】:2020-04-22 02:20:30
【问题描述】:

我在使用 Typecript 的 Google Protobuf 中有一些对象,然后我将其序列化为 JSON 以持久保存到 AWS s3,因为我需要使用这种格式。

但我的要求之一是反序列化(从包含 objInstance.toObject() 生成的 JSON 的字符串)。

有什么方法可以使用为它生成的代码吗?所有内部类(jspb.Message)都不包含任何与反序列化相关的方法,除了deserializeBinary,这不是我需要的。

Node/Typescript 中关于 google protobuf 的文档现在很差,甚至查看了 repo 中的测试 (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

【问题讨论】:

  • 为什么/什么你序列化为 JSON? protobuf 的重点是序列化二进制文件。没有什么能阻止你将二进制文件转换为 base64 字符串,然后再返回,如果你真的需要的话。
  • 嗨 Meirion,正如我在第一行所说,我需要使用 S3 Select (aws.amazon.com/blogs/aws/s3-glacier-select) 在 s3 上处理这些数据,所以我想避免将它序列化两次(作为 json并且当我使用 s3 select 过滤时作为二进制和交叉引用)。如果您有任何疑问,请查看关于我之前添加的问题的最后一个链接,我并不孤单,只是想在这里查看替代方案(如果有的话)。

标签: node.js json typescript protocol-buffers


【解决方案1】:

很遗憾,官方的 JavaScript 实现不支持 JSON。

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

这一行跳过了 JSON 格式的所有测试,因为它没有实现。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2022-01-06
    相关资源
    最近更新 更多