有没有办法在解析协议缓冲时提取字段的名称?

huangapple go评论53阅读模式
英文:

Is there any way to extract name of field when parsing protocol buffer?

问题

我有关于协议缓冲数据的问题。当我使用Java解析和提取要使用的数据时。

message MotherData {
    SonData1 son_data1 = 10;
    SonData2 son_data2 = 10;
}
message SonData1 {
    string my_name = 10;
}
message SonData2 {
    string my_name2 = 10;
}

我想创建一个类似于Map<String, Something>的结构。

  1. put("son_data",/* 现在不关心的SomeData */)
  2. put("son_data2",/* 现在不关心的SomeData */)

为了创建这个映射,我需要提取键作为"son_data"和"son_data2"。所以,我尝试以以下方式提取它。

Mother mother = Mother.parseFrom(/* 包括Mother内容的字节数组输入 */);
mother.getSonData1().getDescriptorForType().getName();
mother.getSonData2().getDescriptorForType().getName();

但它返回的是"SonData1"和"SonData2",而不是"son_data1"和"son_data2"。有没有办法提取用于proto的自定义名称?

英文:

I have problem with protocol buffer data. When paring and extracting the data that I want to use with java.

message MotherData {

    SonData1 son_data1 = 10;
    SonData2 son_data2 = 10;
}
message SonData1 {
    string my_name = 10;
}
message SonData2 {
    string my_name2 = 10;
}

And I want to make Map<String, Something> like this.

  1. put("son_data" ,/* SomeData don't care for now */)
  2. put("son_data2",/* SomeData don't care for now */)

To make this map I need to extract key as "son_data", "son_data2". So, I try to extract it like this way.

Mother mother = Mother.parsefrom(/*Some byte array input including contents of Mother*/);
mother.getSonData1().getDescriptorForType().getName();
mother.getSonData2().getDescriptorForType().getName();

But it returns "SonData1", "SonData2" not "son_data1", "son_data2"
Is there any way to extract own's name used in proto?

答案1

得分: 1

for (Descriptors.FieldDescriptor field : Mother.getDescriptor().getFields()) {
map.put(field.getName(), mother.getField(field));
}

英文:
for (Descriptors.FieldDescriptor field : Mother.getDescriptor().getFields()) {
    map.put(field.getName(), mother.getField(field));
}

huangapple
  • 本文由 发表于 2020年7月22日 10:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63025793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定