Библиотеки сериализации: руководство по буферам протокола Google (Protobuf) с примерами кода

Библиотека Google Protocol Buffers (protobuf) – популярный выбор для сериализации на различных языках программирования. Он обеспечивает независимый от языка способ эффективной сериализации структурированных данных. Вот несколько способов использования protobuf с примерами кода на разных языках:

  1. Метод: буферы протокола в Java

    // Define a message using the protobuf syntax in a .proto file
    message Person {
     string name = 1;
     int32 age = 2;
    }
    // Serialize the message to a byte array
    Person person = Person.newBuilder()
       .setName("John Doe")
       .setAge(25)
       .build();
    byte[] serializedPerson = person.toByteArray();
    // Deserialize the byte array back into the message
    Person deserializedPerson = Person.parseFrom(serializedPerson);
  2. Метод: буферы протокола в Python

    # Define a message using the protobuf syntax in a .proto file
    message Person {
     string name = 1;
     int32 age = 2;
    }
    # Serialize the message to a byte string
    person = Person()
    person.name = "John Doe"
    person.age = 25
    serialized_person = person.SerializeToString()
    # Deserialize the byte string back into the message
    deserialized_person = Person()
    deserialized_person.ParseFromString(serialized_person)
  3. Метод: буферы протокола в C++

    // Define a message using the protobuf syntax in a .proto file
    message Person {
     string name = 1;
     int32 age = 2;
    };
    // Serialize the message to a string
    Person person;
    person.set_name("John Doe");
    person.set_age(25);
    std::string serializedPerson = person.SerializeAsString();
    // Deserialize the string back into the message
    Person deserializedPerson;
    deserializedPerson.ParseFromString(serializedPerson);
  4. Метод: буферы протоколов в Go

    // Define a message using the protobuf syntax in a .proto file
    message Person {
     string name = 1;
     int32 age = 2;
    }
    // Serialize the message to a byte slice
    person := &Person{
       Name: "John Doe",
       Age:  25,
    }
    serializedPerson, err := proto.Marshal(person)
    // Deserialize the byte slice back into the message
    deserializedPerson := &Person{}
    err := proto.Unmarshal(serializedPerson, deserializedPerson)