Search code examples
protocol-buffersgrpcgrpc-javaprotobuf-java

Does protobuf support json properly for nulls since null support is odd?


I am reading through this post on protobuf as I do grpc json to replace existing customers to use our json on grpc ... https://github.com/protocolbuffers/protobuf/issues/1451

builder.setName(null) is not supported since the wire format does 'not' send a value for null. If this is the case, how do I do the json equivalent of these cases

  • "name": 1234
  • "name": 0 //{defaultValue=0 for int} is on the wire
  • "name": null
  • {name not exist}

to me, 'not' calling the setName in protobuf would == {name not exist} on binary format but instead is the name=0 in binary. How to specify in protobuf this case so I can remain compatible with our existing customers in json while switching to protobuf?

FOR Java specifically, we want a setAge() method and if I do NOT call it, the field will not exist. If I call setAge(null), it marshal "age":null. If I call setAge(0), it will marshal "age":0 (default value). If I call setAge(56) non-default value, it marshals "age" : 56

We then want the same thing with protobuf. Sure the wire format MAY have to add additional fields. That is fine and due to the fact that defaults do not get marshalled to the wire so can't tell between null and default value :(. We are ok with the extra data on the wire for KISS for developers.

Is there a proto schema we can use for this as well to have easy setAge(null) methods that marhal to "name":null.

Here is what I am trying to do right now for the above

message SomeMessage {
  string clientId = 1;
  oneof optional_result { // "optional_" prefix here just serves as an indicator, not keyword in proto2
      bool isAccepted = 5;
  }
 }

Then, I see a method getIsAccepted() which returns 'boolean'. I do not see a field for hasIsAccepted(). I am not sure how to define the schema to map to this 'one single' json field.

LOL because I just added grpc json to our platform here and not sure if protobuf can support all json use cases....

https://github.com/deanhiller/webpieces/tree/master/webserver-plugins/plugin-grpc-json

Business Case: Some customers ask we want true if insurance is accepted and false if not accepted and then null if it doesn't exist. We have trinary use-cases here.

thanks, Dean


Solution

  • For the next person(and I use my on SO posts and answers as my own personal knowledge base), I found this amazing article...

    https://itnext.io/protobuf-and-null-support-1908a15311b6