Junior — Middle
Can you explain what Protocol Buffer is and how it is used for data serialization?
sobes.tech AI
Answer from AI
Protocol Buffer (protobuf) is a data serialization mechanism developed by Google. It allows efficient encoding of structured data into a compact binary format that is easy to transmit over a network or store.
Main points:
- You describe the data structure in a special
.protofile. - The protobuf compiler generates classes for the chosen programming language (e.g., Java).
- These classes allow serializing objects into binary format and deserializing back.
Advantages of protobuf:
- Compactness and speed compared to text formats (JSON, XML).
- Clear data schema, which facilitates validation and evolution of the format.
Example of usage in Java:
// Suppose you have a generated Person class
Person person = Person.newBuilder()
.setName("Ivan")
.setId(123)
.build();
// Serialization to byte array
byte[] data = person.toByteArray();
// Deserialization from byte array
Person person2 = Person.parseFrom(data);