Bartek Maciejiczek
Bartek Maciejiczek

Reputation: 159

Represent an array of objects as a protobuf message

I would like to create a protobuf message which represents an array of objects.

Example

[
  {
    "firstKey": "firstValue",
    "secondKey": "secondValue",
  },
  {
    "firstKey": "firstValue",
    "secondKey": "secondValue",
  },
  ...
]

Pseudo code (not a valid syntax)

syntax = "proto3";

message Entry {
  string firstKey = 1;
  string secondKey = 2;
}

repeated message Response {
  ...Entry;
}

I cannot find a way to do this. Is it even possible or am I forced to nest it like this?

syntax = "proto3";

message Entry {
  string firstKey = 1;
  string secondKey = 2;
}

message Response {
  repeated Entry data = 2;
}

Upvotes: 4

Views: 13692

Answers (2)

Kumar
Kumar

Reputation: 49

syntax = "proto3";

message SingleObject {
  string name = 1;
  int32 age = 2;
}

message ObjectArray {
  repeated SingleObject objects = 1;
}

Upvotes: 4

Daniel Gibson
Daniel Gibson

Reputation: 11

You can't achieve this directly with Protocol Buffers because ProtoBuf is a binary serialization format, and its messages are structured differently from JSON arrays. ProtoBuf messages don't inherently have a root array like JSON.

Instead you can achieve this in your application code by constructing a JSON array and serializing/wrapping it with an object matching the ProtoBuf Message.

Upvotes: 1

Related Questions