Lahiru Udayanga
Lahiru Udayanga

Reputation: 369

Google protobuf repeated fields with C++

I have a requirement to build the following Metadata message using serialized key value pairs in C++.

message MetadataValue {
  string key = 1;
  google.protobuf.Value value = 2;
}

message Metadata {
  repeated MetadataValue metadata = 1;
}

So I can have the values for MetadataValue from the following for statement in C++.

Metadata metadata; 
  if (buffer.has_value()) {
    auto pairs = buffer.value()->pairs();
    for (auto &p : pairs) {
      MetadataValue* metadataValue = metadata.add_metadata();
      metadataValue->set_key(std::string(p.first));
      // I don't know how to set the value for google.protobuf.Value 
    }
  }

My question is whether my approach is correct ? Are there better alternatives and how to set the google.protobuf.Value in that above scenario ? A simple code snippet with the answer is much appreciated.

Upvotes: 1

Views: 3754

Answers (1)

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

I think this code works, I just checked the generated APIs by protoc.

If the typeof(p.second) is not a google::protobuf::Value, you need to add conversion like

auto v = google::protobuf::Value();
v.set_number_value(p.second);
// or p.second is string
// v.set_string_value(p.second);
Metadata metadata; 
  if (buffer.has_value()) {
    auto pairs = buffer.value()->pairs();
    for (auto &p : pairs) {
      MetadataValue* metadataValue = metadata.add_metadata();
      metadataValue->set_key(std::string(p.first));
      *metadataValue->mutable_value() = p.second;
      // I don't know how to set the value for google.protobuf.Value 
    }
  }

And I am using protoc version 3

syntax = "proto3";
import "google/protobuf/struct.proto";
message MetadataValue {
  string key = 1;
  google.protobuf.Value value = 2;
}

message Metadata {
  repeated MetadataValue metadata = 1;
}

Upvotes: 1

Related Questions