最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to encode messages with “map” using google-protobuf in JavaScript? (protocol buffers) - Stack Overflow

programmeradmin0浏览0评论

I wanna ask that how to encode (serialization) Map Fields.

According to the google guide, "JavaScript Generated Code" contains the following function for Map Fields. The decoding function (getFooMap()) is generated. But I couldn't find the encoding functions or guide for map type anywhere. (I thought there would be a function like setXXXMap(), but I couldn't find it.)

How should I encode Map Fields?

Map Fields

For this message with a map field:

message Bar {}

message Baz {
  map<string, Bar> foo = 1;
}

the piler generates the following instance method:

getFooMap(): Returns the Map containing foo's key-value pairs. You can then use Map methods to interact with the map.

I wanna ask that how to encode (serialization) Map Fields.

According to the google guide, "JavaScript Generated Code" contains the following function for Map Fields. The decoding function (getFooMap()) is generated. But I couldn't find the encoding functions or guide for map type anywhere. (I thought there would be a function like setXXXMap(), but I couldn't find it.)

How should I encode Map Fields?

https://developers.google./protocol-buffers/docs/reference/javascript-generated#map

Map Fields

For this message with a map field:

message Bar {}

message Baz {
  map<string, Bar> foo = 1;
}

the piler generates the following instance method:

getFooMap(): Returns the Map containing foo's key-value pairs. You can then use Map methods to interact with the map.

Share Improve this question edited Jul 3, 2020 at 5:59 Azeem 14.8k4 gold badges34 silver badges51 bronze badges asked Jul 3, 2020 at 3:00 justinjustin 131 silver badge3 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Here's an exmaple:

map-test.proto

syntax = "proto3";

package test;

message Table {
    string label = 1;
    map<string, int32> data = 2;
}

Generate protobuf:

$ protoc --js_out=import_style=monjs,binary:. ./map-test.proto

map-test.js

var proto = require('./map-test_pb');

// Serialization

var msg = new proto.Table();
msg.setLabel("Test");
msg.getDataMap().set("a", 1);
msg.getDataMap().set("b", 2);
msg.getDataMap().set("c", 3);

var serialized = msg.serializeBinary();

// Deserialization

var deserialized = proto.Table.deserializeBinary(serialized);
console.log(deserialized.getLabel());

deserialized.getDataMap().forEach(function(v, k) {
    console.log(k, v);
});

// console.log(deserialized.getDataMap().entries());
// console.log(deserialized.getDataMap().get("a"));

Output:

Test
a 1
b 2
c 3

You can use set() and get() methods of the map to store and retrieve values; forEach() to iterate through all the KV pairs, etc. Check these map tests for more examples.

发布评论

评论列表(0)

  1. 暂无评论