daltonfury42
daltonfury42

Reputation: 3734

Protobuf-java: Merge two proto objects without concatenating repeated fields

I want to merge two complex proto objects protoA and protoB of the same type, where if a field is set in both the objects, the value of protoB should be set in the resulting proto.

I could use the .mergeFrom() function:

protoA.toBuilder().mergeFrom(protoB).build()

but according to the docs, repeated fields will be concatenated.

mergeFrom(Message other): (builder only) merges the contents of other into this message, overwriting singular scalar fields, merging composite fields, and concatenating repeated fields.

I don't want this behaviour. Is there a elegant way to do this than to manually set each repeated fields?

Upvotes: 4

Views: 4738

Answers (1)

Paplusc
Paplusc

Reputation: 1130

In FieldMaskUtil from protobuf there is an option to merge overriding existing fields.

It has a MergeOptions where you can configure setReplaceRepeatedFields(true); it will merge protoB into protoA taking protoB fields when repeated.

I will write you an example:

FieldMaskUtil.MergeOptions options = 
      new FieldMaskUtil.MergeOptions().setReplaceRepeatedFields(true);

// Now we get all the names of the fields in your proto
List<String> names = YourObjectProto.YourObject.getDescriptor().getFields()
           .stream().map(Descriptors.FieldDescriptor::getName)
           .collect(Collectors.toList());

FieldMaskUtil.merge(FieldMaskUtil.fromStringList(names),
      protoB, protoA.toBuilder(),options);

Upvotes: 3

Related Questions