Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set repeated fields in protobuf before building the message?

Let's say I have a Message with a repeated field:

Message Foo {
    repeated Bar bar = 1;
}

Now I want to insert n Bar objects into the field bar, each is created in a loop.

for (i=0; i < n; i++){
    //Add Bar into foo
}
//Build foo after loop

Is this possible or do I need all n bar fields at the same time before building the foo Object?

like image 443
Gobliins Avatar asked Mar 20 '15 15:03

Gobliins


People also ask

Are repeated fields ordered in Protobuf?

Yes, repeated fields retain the order of items. From Google's Protocol Buffers encoding specification: The order of the elements with respect to each other is preserved when parsing, though the ordering with respect to other fields is lost.

What is repeated field in Protobuf?

repeated : this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.

How do you delete a repeated field in Protobuf?

For Protobuf v2 You can use the DeleteSubrange(int start, int num) in RepeatedPtrField class. If you want to delete a single element then you have to call this method as DeleteSubrange(index_to_be_del, 1) . It will remove the element at that index.

What is repeated in gRPC?

gRPC services provide two ways of returning datasets, or lists of objects. The Protocol Buffers message specification uses the repeated keyword for declaring lists or arrays of messages within another message. The gRPC service specification uses the stream keyword to declare a long-running persistent connection.


2 Answers

When you use the protoc command to generate the java object it will create a Foo Object which will have its own builder method on it.

You will end up doing something like this

//Creates the builder object 
Builder builder = Package.Foo.newBuilder();
//populate the repeated field.
builder.addAll(new ArrayList<Bar>());
//This should build out a Foo object
builder.build(); 

To add individual objects you can do something like this.

    Bar bar = new Bar();
    builder.addBar(bar);
    builder.build();

Edited with the use case you've requested.

like image 74
Venki Avatar answered Oct 27 '22 02:10

Venki


List<Bar> barList= new Arraylist();
barList.add(new Bar());

Then set the list of Bar in the Foo

Foo foo =  Foo.newBuilder()
        .addAllBar(barList)
        .build;

You can set only one value for Bar

Foo foo =  Foo.newBuilder()
        .addBar(new Bar())
        .build;
like image 45
Sneha Mule Avatar answered Oct 27 '22 01:10

Sneha Mule