When deserializing Jason to ProtoBuffer message null values set to default values

Viewed 209

I'm using ProtoBuffer 3 and I have a message that is composed of multiple fields and some of them are other messages that contains some (or all) nullable values.

For example:

message MainMessage {
   google.protobuf.StringValue title = 1;
   NotNullable sub1 = 2;
   Nullable sub2 = 3;
   NotNullable sub3 = 4;
}

message NotNullable {
    int64 id = 1;
    string value = 2;
}

message Nullable {
    google.protobuf.Int64Value id = 1;
    google.protobuf.Int64Value value = 2;
}

I'm getting the message as a son and I want to deserialize it using the following code:

String json = "{\"title\":{\"value\":\"A nice title\"},\"sub1\":{\"id\":{\"value\":1}}}";
MainMessage.Builder message = MainMessage.newBuilder();
JsonFormat.parser().merge(json, message);

After running the code above the object that I'm getting contains all of the fields (even that sub2 and sub3 are not in the JSON) where the missing data is init to the default value.

for example, the following code will return true:

assertTrue(message.getSub2().getId().isInitialized())
assertTrue(message.getSub3().isInitialized())

I checked the documentation but couldn't find a way to tell the parse not to set those fields - is there such an option?

1 Answers

It seems like this article solves the issue: https://itnext.io/protobuf-and-null-support-1908a15311b6

The way I've implemented it is as follow (sorry for the confusion with the names - I wanted to keep the original names):

message MainMessage {
   google.protobuf.StringValue title = 1;
   NotNullable sub1 = 2;
   Nullable sub2 = 3;
   NotNullable sub3 = 4;
}

message NotNullable {
    int64 id = 1;
    string value = 2;
}

message Nullable {
    google.protobuf.Int64Value id = 1;
    google.protobuf.Int64Value value = 2;
}

message AllowNullable {
    oneof kind {
       google.protobuf.NullValue null = 1;
       Nullable value = 2;
}

Now all that is required is to use the has method before calling the value to check whether or not it's null

For example:

if(message.getSub3().hasValue()) {
   // do something...
}
Related