【问题标题】:Protobuf-java: Merge two proto objects without concatenating repeated fieldsProtobuf-java:合并两个 proto 对象而不连接重复字段
【发布时间】:2021-06-10 12:48:45
【问题描述】:

我想合并两个相同类型的复杂原型对象protoAprotoB,如果在这两个对象中都设置了一个字段,则应该在生成的原型中设置protoB的值。

我可以使用.mergeFrom() 函数:

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

但根据文档,重复的字段将被连接起来。

mergeFrom(Message other):(仅限构建器)将 other 的内容合并到此消息中,覆盖单数标量字段,合并复合字段,并连接重复字段。

我不想要这种行为。有没有比手动设置每个重复字段更优雅的方法?

【问题讨论】:

    标签: java protocol-buffers grpc grpc-java


    【解决方案1】:

    在来自 protobuf 的 FieldMaskUtil 中,有一个合并覆盖现有字段的选项。

    它有一个MergeOptions,您可以在其中配置setReplaceRepeatedFields(true);,它会在重复时将protoB合并到protoA中并获取protoB字段。

    我给你写个例子:

    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);
    

    【讨论】:

    • 谢谢,这不尊重超过一级的选项。见here。所以你最终会在子消息上调用 mergeFrom 。 ://
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2021-09-11
    • 2016-12-31
    • 2018-01-26
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多