Protobuf getAllFields() 未按预期工作 [英] Protobuf getAllFields() not working as expected

查看:92
本文介绍了Protobuf getAllFields() 未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析第三方发送的 protobuf 消息并进行处理.我在访问字段时遇到问题的部分如下所示:

I need to parse protobuf messages sent by third party and process those. A part where I am facing an issue in accessing fields looks like following:

ext {\n  is_foo: NO\n  is_bar: false\n  
12: \"fgyhcbho-4594-34545-gbvj\"\n  13: 0\n } 

我主要对访问字段名称12"的值感兴趣.但是, getAllFields().entrySet() 仅返回 2 个条目 - is_foo 和 is_bar .所以我无法获得字段12"的值fgyhcbho-4594-34545-gbvj".

I am mainly interested in accessing the value of the field name "12". However, getAllFields().entrySet() returns only 2 entries - is_foo and is_bar . So I am unable to get the value "fgyhcbho-4594-34545-gbvj" of the field "12".

以下是我使用 protobuf(v2.6) 编译器编译以生成 .java 文件的 .proto 文件的一部分:

Following is a part of my .proto file which I compiled using protobuf(v2.6) compiler to generate .java file:

message Ext {
    optional bool is_foor = 1;      
    optional bool is_bar = 2;  
    optional string uid = 12;  
    optional int32 did = 13;  
 }

我的 .java 文件包含方法 hasUid() 和 getUid().但是我收到的 protobuf 消息包含字段12"而不是uid".因此,当我尝试反序列化为 Java 时,它只是不包含该字段,也不包含未知字段.

My .java file contains method hasUid() and getUid(). But the protobuf message I receive contains field "12" and not "uid". So when I try to deserialize to Java, it just does not contain that field and no unknown fields either.

以下是我使用的代码片段:

Below is the code snippet I am using:

if (this.protoReq.getExt() != null) {
        for (Map.Entry<FieldDescriptor, Object> entry : this.protoReq.getExt().getAllFields().entrySet()) {
            FieldDescriptor field = entry.getKey();
            if (field.getName().equals("12")) {
                Object value = entry.getValue();
                if (value != null) {
                   //do something
                }
                break;
            }
        }
    }

我错过了什么吗?有没有其他方法可以访问它?任何帮助表示赞赏.谢谢.

Am I missing something? Is there any other way to access it ? Any help is appreciated. Thank you.

推荐答案

当您看到带有数字标签的字段时,这意味着该字段是未知字段 -- 在线上看到的数字与定义的任何字段名称都不匹配在 .proto 文件中.

When you see fields with numeric labels, it means that the field is an unknown field -- the number seen on the wire doesn't match any field name defined in the .proto file.

getAllFields() 只返回 known 字段,因为它返回一个描述符->值映射,描述符只存在于已知字段.

getAllFields() only returns known fields, because it returns a descriptor->value map, and descriptors only exist for known fields.

要读取未知字段,您需要调用 message.getUnknownFields(),它会返回一个 UnknownFieldSet.该对象将未知字段编号映射到值.

To read unknown fields, you need to call message.getUnknownFields(), which returns an UnknownFieldSet. That object maps unknown field numbers to values.

这篇关于Protobuf getAllFields() 未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆