简体   繁体   中英

Converting protobuf Dynamic Message returned by gRPC call into JSON or similar object

I am making a gRPC call to a server using reflection which returns Dynamic Message as the response message. Now, although this object looks similar to a nested object, its structure is slightly different from a JSON. This makes fetching of values based on fields, like

someObject.get(someField) 

difficult. One way is to parse this message to an object and then fetch the desired values. Any suggestions on parsing here?

This is the class getting returned:

com.google.protobuf.DynamicMessage

But, although it looks like a nested JSON, we can't fetch values based on fields.

To have an overview of the shema, this is how the response looks:

field1 {
  key1: "value1"
}
field2 {
  key1: "value1"
  key2: value2
  key3 {
    netsed_key_1: "nested_val_1"
    netsed_key_2: "nested_val_2"
  }
  key4 {
    netsed_key_1: "nested_val_1"
    netsed_key_2: "nested_val_2"
  }
}

Try this:

FieldDescriptor fieldDescriptor = message.getDescriptorForType().findFieldByName("someField");
Object value = message.getField(fieldDescriptor);

To get a list of all the fields:

Map<Descriptors.FieldDescriptor, Object> allFields = message.getAllFields();

To get a nested value do this:

Message subMessage =
    (Message)message.getField(
        message.getDescriptorForType().findFieldByName("field3"));
Message subSubMessage =
    (Message)subMessage.getField(
    subMessage.getDescriptorForType().findFieldByName("key3"));
String subSubSubMessage veryNestedString =
    (String)subSubMessage.getField(
    subSubMessage.getDescriptorForType().findFieldByName("netsed_key_1"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM