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

tuk :

I have a protobuf message which when converted to string using TextFormat.printToString() looks like below:-

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"
}

The proto definition looks like below

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;
}

Is it possible to display description as the first field while converting the proto message to string using TextFormat.printToString() ?

Petr Janeček :

As you probably understand right now, the message is being encoded in the order of the fields - the order of the tags. This is guaranteed by the Message#getAllFields() method which

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

Therefore, if you need your description field to be the first one, you'll either need to deprecate and move all the fields 1-9 to numbers 11-19, or deprecate the description field, and create a new message similar to this:

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

Sorry, there aren't many better options, the order of fields in protobuf is (by design) not very important / customizable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=344585&siteId=1