如何在nodejs中将对象转换为protobuf数据

问题描述

如果我有如下定义的 proto3 消息

message Log {
  string object = 1;
  string key_result = 2;
  string review = 3;
  repeated string tag = 4;

  string begin_at = 5;
  string end_at = 6;
  string created_at = 7;
  string id = 8;
}

带有protoc--js_out--ts_out生成类似

export class Log extends jspb.Message {
  getobject(): string;
  setobject(value: string): void;

  getKeyResult(): string;
  setKeyResult(value: string): void;

  getReview(): string;
  setReview(value: string): void;

  clearTagList(): void;
  getTagList(): Array<string>;
  setTagList(value: Array<string>): void;
  addTag(value: string,index?: number): string;

  getBeginAt(): string;
  setBeginAt(value: string): void;

  getEndAt(): string;
  setEndAt(value: string): void;

  getCreatedAt(): string;
  setCreatedAt(value: string): void;

  getId(): string;
  setId(value: string): void;

  serializeBinary(): Uint8Array;
  toObject(includeInstance?: boolean): Log.AsObject;
  static toObject(includeInstance: boolean,msg: Log): Log.AsObject;
  static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
  static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
  static serializeBinaryToWriter(message: Log,writer: jspb.BinaryWriter): void;
  static deserializeBinary(bytes: Uint8Array): Log;
  static deserializeBinaryFromreader(message: Log,reader: jspb.BinaryReader): Log;
}

通过 Log 方法toObject 类转换为 Object 很简单。但是要将对象转换为类,我需要手动设置每个字段。

export function toLog(log: Log.AsObject): Log {
    const t = new Log
    t.setobject(log.object)
    t.setKeyResult(log.keyResult)
    t.setReview(log.review)
    t.setTagList(log.tagList)
    t.setBeginAt(log.beginAt)
    t.setEndAt(log.endAt)
    t.setCreatedAt(log.createdAt)
    t.setId(log.id)
    return t
}

有没有更简单的方法来执行这样的任务?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...