简体   繁体   中英

Google Protobuf - Deserialize from JSON in Typescript

I have some objects in Google Protobuf using Typecript and I'm serializing then to JSON to persist to AWS s3, as I need to work with then in this format.

But one of the requirements I have is to deserialize (from a string containing the JSON generated by objInstance.toObject()).

Is there any way to make it possible using the code generated for it? All the internal classes (jspb.Message) does not contain any method related to deserialization EXCEPT deserializeBinary, that is not what I need.

The documentation regarding google protobuf in Node/Typescript is very poor right now, even looked at the tests in the repo ( https://github.com/protocolbuffers/protobuf/tree/master/js )

Here's the functions in the generated code:

  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;

I found one issue referencing this: toObject -> Protobuf

Unfortunately, the official JavaScript implementation does not support JSON.

You can see it in the conformance tests: https://github.com/protocolbuffers/protobuf/blob/0110ff565951ea52af37d6f155197048c378abe3/conformance/conformance_nodejs.js#L76

This line skips all the tests for the JSON format because it is not implemented.

But there are alternative protobuf implementations in TypeScript. For example, protobuf-ts (this is a shameless plug, I am the author). It supports all features of the canonical proto3 JSON format. It passes all conformance tests. And it has a seriously smaller footprint than google-protobuf ~40kb vs ~400kb .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM