在 java 中使用 TextFormat 将 protobuf 消息转换为字符串时如何控制字段的顺序?

How to control the order of field while converting a protobuf message to string using TextFormat in java?

我有一条 protobuf 消息,使用 TextFormat.printToString() 将其转换为字符串时如下所示:-

deploymentDef {
  id: "PX3C1ED"
  default: true
  type: ONPREM
  limits {
    clusterSize: 3
    limits {
      numVMs: 18000
      numVMsWithFlows: 18000
      activeFlows: 6000000
      totalFlows: 24000000
      flowPlanning: 4000000
      numDevices: 40
    }
  }
  isEnterprise: false
  brickSize: XLARGE
  clusterSize: 3
  description: "Default Role, Non-Enterprise, App-Discovery and Vf services stopped"
}

原型定义如下所示

message DeploymentDef {
    optional string id = 1;
    optional bool default = 2;
    optional DeploymentType type = 3;
    optional PlatformClusterLimits limits = 4;
    repeated Role roles = 5;
    optional bool isEnterprise = 6;
    optional Configs overrides = 7;
    optional BrickSize brickSize = 8;
    optional int32 clusterSize = 9;
    optional string description = 10;
}

在使用 TextFormat.printToString() 将原型消息转换为字符串时,是否可以将 description 显示为第一个字段?

正如您现在可能理解的那样,消息是按照字段的顺序——标签的顺序进行编码的。这是由 Message#getAllFields() 方法保证的

is guaranteed to be a sorted map, so iterating over it will return fields in order by field number

因此,如果您需要将描述字段放在第一个,则需要弃用所有字段 1-9 并将其移动到编号 11-19,或者弃用 description 字段,并创建一条与此类似的新消息:

message Deployment {
    optional string description = 1;
    required DeploymentDef deploymentDef = 2;
}

抱歉,没有太多更好的选择,protobuf 中的字段顺序(按设计)不是很重要/可自定义。