3

I have met some problems about changing the value in my protobuff message. This is the proto file.

message Info {
  repeated InfoUnit unit = 1;  
}
message InfoUnit {
  optional uint64 id = 1;
  repeated DateUnit date_unit = 2;
}
message DateUnit {
  optional uint64 date = 1;
}

My task is simple. I get an Info message, then update Info's InfoUnit list. For example:

  1. update the first UnitInfo's first DateUnit's date = 2.

  2. add a new UnitInfo to Info with default values.

At first, I think I can just get the list and then update it.

Info.Builder builder = infoMessage.toBuilder();
List<InfoUnit> list = builder.getInfoUnitList();
//first infoUnit, first dataUnit, 2
update(list.get(0), 0, 2);
list.add(InfoUnit.newBuilder()...........build())

but finally this does not work.

I find an explain in this website: Making a small change to a Java protocol buffers object

I do not understand and I don't find a good way to solve this problem.

So I change to a new plan, but this is complex.

Info.Builder builder = infoMessage.toBuilder();
//copy the builder list
List<InfoUnit.Builder> builderList = new ArrayList<InfoUnit>(builder.getInfoUnitBuilderList());

//finish update and add
update(....);

//clear the InfoUnit list
builder.clearInfouNIT();
//rebuild the list
for(InfoUnit.Builder infoUnitBuilder: builderList)
    builder.addInfoUnit(infoUnitBuilder);
//rebuild this Info
builder.build();

I copy the InfoUnit's builder list to update, then clear the former InfoUnit list and use the copy to rebuild the InfoUnit list. You may find that the DataUnit is also a list, so I do this work again. I don't write the DataUnit's update codes here, just use 'update' to replace briefly.

Of course this worked. But I believe there must be a better way to update the value of repeat type in message. If someone has good ideas or has some questions about my situation, leave message to me. Expect anyone's reply :)

Andy
  • 31
  • 1
  • Protocol buffers are not well suited for in place edits, and few APIs exist to help you. You can append field changes, but that doesn't work for "repeated" - it just adds more values. And in proto3 you cannot use append to update a value to be zero, for example, because a zero is never written. – Marc Gravell Jul 01 '17 at 19:38

0 Answers0