1

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.com/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 compiler 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.

Azeem
  • 11,148
  • 4
  • 27
  • 40
justin
  • 13
  • 1
  • 3

1 Answers1

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=commonjs,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.

Azeem
  • 11,148
  • 4
  • 27
  • 40