如何实现包含带有自定义键的地图的Google Protobuf

问题描述

我想创建一个protobuf,它返回包含自定义键的映射。当我尝试制作一个时,出现错误Key in map fields cannot be float/double,bytes or message types。我想知道是否有解决方法

我正在尝试创建以下类型的地图(如图所示):

message Name {
  string first_name = 1;
  string last_name = 2;
}

message GetNameResp {
  map<Name,string> name_info = 1;
}

那么,这里的Name可能是地图的钥匙吗?我唯一能找到的解决方案是序列化映射,然后返回为repeated值。

谢谢!

解决方法

地图键可能不是消息类型:

https://developers.google.com/protocol-buffers/docs/proto3#maps

您将不得不在代码中解决此问题。

您可以将Name转换为字符串:

  • 序列化protobuf消息
  • 封送至JSON
  • 散列值(尽管您可能会发生冲突)