Jordan H
Jordan H

Reputation: 55715

Decode an array of messages in protobuf.js

In our node.js application we need to deserialize a Buffer which we know contains multiple objects. With protobuf-net this was done like so:

var stream = new MemoryStream(byteData);
List<Schema.Object> objects = ProtoBuf.Serializer.Deserialize<List<Schema.Object>>(stream);

I am now trying to do the same with protobuf.js. I haven't found an example where it creates an array of the model objects, only a single model object, like so:

const Object = root.lookupType('model.Object');
const message = Object.decode(byteData); //this creates one object but the buffer contains multiple objects

How do you create an array of objects, rather than a single object using protobuf.js?

Here's how the data is being serialized:

try
    {
        using (var stream = new MemoryStream())
        {
            ProtoBuf.Serializer.Serialize(stream, objects);
            Stream.Position = 0;

            // Return the serialized byte array.
            return stream.ToArray();
        }
    }
    finally {}
}

Upvotes: 1

Views: 2277

Answers (1)

Jordan H
Jordan H

Reputation: 55715

Found a solution. You can wrap the Object with another message containing a repeated entry. Then when it's decoded, it will be an array of Objects.

In the .proto file:

message ObjectCollection {
  repeated Object objects = 1;
}

Upvotes: 2

Related Questions