3

I have a message defined quotation_item.proto file which has google.protobuf.Struct field to parse metadata JSON.

message QuotationItemEntry {
    // Other fields
    google.protobuf.Struct metadata = 15;
}

Also metadata field is defined in Java entity class

public class QuotationItem {
    // Other entity fields
    private Map<String, Object> metadata;
}

I want to store the QuotationItemEntry object passed in gRPC request using spring boot application but not able to convert google.protobuf.Struct field in java.util.Map<String, Object>.

jaymil
  • 31
  • 1
  • 2

3 Answers3

1

In Java, google.protobuf.Struct's field values are not supported in their native representations. Instead, they are wrapped by com.google.protobuf.Value. So with google.protobuf.Struct#getFieldsMap() method, the result is a Map<String, Value>. You would need to populate entry values manually.

voidzcy
  • 520
  • 2
  • 7
0

I think you can stream over metadata keys and collect them as a map. This could solve your problem.

    public Map<String, String> getMetadataMap(Metadata metadata) {
            Map<String, String> metadataMap = metadata.keys().stream().collect(
                Collectors.toMap(
                    key -> key,
                    key -> metadata.get(Metadata.Key.of(key,
                                        Metadata.ASCII_STRING_MARSHALLER))));
            return metadataMap;
          }
Dharman
  • 30,962
  • 25
  • 85
  • 135
abhilash_goyal
  • 711
  • 1
  • 10
  • 31
0

Solution for kotlin:

fun Struct.toMap(): Map<String, Any?> =
    this.fieldsMap.mapValues { it.value.toAny() }

fun Value.toAny(): Any? =
    when (kindCase) {
        NULL_VALUE -> null
        NUMBER_VALUE -> numberValue
        STRING_VALUE -> stringValue
        BOOL_VALUE -> boolValue
        STRUCT_VALUE -> structValue.toMap()
        LIST_VALUE -> listValue.valuesList.map { it.toAny() }
        else -> error("Incorrect protobuf value $this")
    }

Usage:

val map: Map<String, Any?> = youProtoStruct.toMap()
Sergey Bulavkin
  • 2,325
  • 2
  • 17
  • 26