来自 json 的 Proto 反序列化将在新字段或未知枚举值上失败

Proto deserialization from json will fail on new fields or unknown enum values

proto 旨在引入新字段不会破坏在旧版本上运行的代码。

但是,如果您使用 protobuf-java-utiljava 中使用 json 转换,那么您的旧代码将在现有代码未知的新字段或新枚举值上中断...

我在 github 上打开了一个 issue,但没有引起任何注意。希望在这里得到一些答案。

给出这样的消息

message Msg {
    required string sender = 1;
    required string message = 2;
}

如果我们将其转换为 json 并使用

打印
JsonFormat.printer().print(msg)

我们会得到这个结果

{
  "sender": "me",
  "message": "message"
}

如果我们使用其构建器

将此 json 解码为 Msg
JsonFormat.parser().merge(json, builder)

我们会得到预期的结果...但是如果我们尝试用额外的 extra 字段

解码类似的 json
{
  "sender": "me",
  "message": "message",
  "extra" : "some extra stuff"
}

我们将因这个异常而失败

com.google.protobuf.InvalidProtocolBufferException: Cannot find field: extra in message proto.Msg

怎么没人关心这个问题?到目前为止,我唯一的解决方案是从头开始编写一个解析器,在解析时将忽略未知字段和未知枚举值...

有没有我忽略的地方或者人们根本不使用向后兼容功能?

这已被 google 修复,构建器提供了忽略未知字段的选项。