英文:
How to represent a HashMap<Object, Double> instance in ProtoBuffer?
问题
I need to include an instance of the following class as a field in a protocol buffer schema:
public final class Metrics extends HashMap<Object, Double> {
}
but when I add something like:
map<bytes, double> metrics = 2;
I effectively get the message "Map key cannot be float, double, bytes, message, or enum types".
One approach I've thought of was to turn the objects (keys) into bytes and then into base64 keys to create a new map, which would be the actual map to be sent to the wire (then reverse these operations when it got to the other side). But this seems too expensive, and I feel like I would have to create an instance of the input streams (and close them) for each entry.
Is there a known approach for this case? How would you do it?
I did not find any example of this.
Thanks
英文:
I need to include an instance of the following class as a field in a protocol buffer schema:
public final class Metrics extends HashMap<Object, Double> {
}
but when I add something like:
map<bytes, double> metrics = 2;
I effectively get the message Map key cannot be float, double, bytes, message, or enum types
.
One approach I've thought of was to turn the objects (keys) into bytes and then to base64 keys to create a new map, which would be the actual map to be sent to the wire (then reverse these operations when it got to the other side). But this seems too expensive and I feel like I would have to create an instance of the input streams (and close them) for each entry.
Is there a known approach for this case? How would you do it?
I did not find any example of this.
Thanks
答案1
得分: 1
你可以使用键值对列表来模拟映射(在proto3引入映射之前是这样做的),并将它们回溯到proto2:
message Metric {
bytes key = 1;
double value = 2;
}
repeated Metric metrics = 2;
英文:
You can emulate map with a list of key-value pairs (this is how it was done before introduction of maps in proto3 and backporting them to proto2):
message Metric {
bytes key = 1;
double value = 2;
}
repeated Metric metrics = 2;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论