Ethan Yim
Ethan Yim

Reputation: 85

Java: JSON String -> LIST OF Protobuf

JsonFormat.parser().merge(json_string, builder);

I know that I can use the above code for turning a json string into a Protobuf java object. But what if my json_string has multiple items (list) and I want to turn it into LIST OF Protobuf java objects?

For example my json string being:

[
  {"id": 1},
  {"id": 2},
  {"id": 3}
]

how can I turn this into a List containing 3 Protobuf objects in java?

Upvotes: 1

Views: 3968

Answers (1)

fizzie
fizzie

Reputation: 691

I don't think that's a feature as such, because JsonFormat is designed specifically to match the canonical proto3 JSON mapping, which does not have any concept of "top-level" arrays, only arrays for representing repeated fields.

That said, likely-to-work (though annoyingly inelegant) workarounds include at least:

Using a wrapper message with a repeated field

If you define a wrapper message that just contains a single repeated field holding your actual payload message:

message Item {
  int64 id = 1;
}

message ItemList {
  repeated Item items = 1;
}

You could parse your JSON array into a list by surrounding it with the necessary bits to make it a valid instance of your wrapper message:

ItemList.Builder builder = ItemList.newBuilder();
JsonFormat.parser().merge("{\"items\":" + json_string + "}", builder);
List<Item> items = builder.getItemsList();

Using the overload of the merge method that takes a java.io.Reader, you could probably accomplish this without actually concatenating any strings (in case it's a very large message and that matters), though it would need something similar to the SequenceReader, which doesn't exist in the standard library.

Using a separate JSON library

The API would depend on which one of them you pick, but chances are many of them would allow you to:

  1. Read in the JSON array.
  2. Iterate over the array items as JSON objects.
  3. Serialize the object back into a buffer.
  4. Use JsonFormat to parse the individual objects.

Upvotes: 1

Related Questions