proto
的设计目的是引入新字段不应破坏在旧版本上运行的代码。
但是,如果您使用 json
在 java
中使用 protobuf-java-util
转换,那么您的旧代码将在现有代码未知的新字段或新枚举值上中断...
我在 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)
我们会得到预期的结果......但是如果我们尝试使用额外的
json
字段解码类似的 extra
{
"sender": "me",
"message": "message",
"extra" : "some extra stuff"
}
我们将因此异常而失败
com.google.protobuf.InvalidProtocolBufferException: Cannot find field: extra in message proto.Msg
怎么没人关心这个问题?到目前为止,我唯一的解决方案是从头开始编写一个解析器,在解析时将忽略未知字段和未知枚举值......
有没有我忽略的东西,或者人们根本不使用向后兼容功能?
最佳答案
谷歌已经修复了这个问题,构建器提供了忽略未知字段的选项。
关于java - 来自 json 的 Proto 反序列化将在新字段或未知枚举值上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37537023/