2

I'm using Protocol Buffers from Google in my Java projects.

When I define message like that:

message Event {
  int32 action = 1;
}

and save value zero as an action, then value zero won't be saved. It's able to save all integer values except for zero.

I even found it in my decompiled code generated by Protocol Buffers:

...
public void writeTo(CodedOutputStream output) throws IOException {
  if (this.action_ != 0) {
    output.writeInt32(1, this.action_);
  }
  ...
}

Do you know, how can I force saving zeros? Or it's not possible and simply forbidden by Protocol Buffers design?

Piotr Wittchen
  • 3,853
  • 4
  • 26
  • 39
  • AFAIK you can change default value, so it will skip some other value. – talex Mar 31 '21 at 15:43
  • @talex only in proto2; in proto3, explicit assignment tracking (presence tracking) has been added back - you can now use `optional int32 action = 1;` and it should work in the expected way – Marc Gravell Mar 31 '21 at 16:00
  • I've added more detail here: https://stackoverflow.com/a/66891274/23354 – Marc Gravell Mar 31 '21 at 16:04
  • So if I just add `optional` it will allow to save zeros? It's weird syntax for me because I don't want this field to be optional (in java sense). I want it to be required and have possibility to save zero value. – Piotr Wittchen Mar 31 '21 at 19:06
  • Same problem as @PiotrWittchen. What if I want it to be mandatory and have an explicit zero there? – Capitano Giovarco Oct 25 '22 at 07:35
  • That's the design of protocol buffers. You have to take it into consideration in your project. – Piotr Wittchen Oct 25 '22 at 12:36

0 Answers0