package tutorial;
option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
message AddressBook {
repeated Person person = 1;
}
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
protoc -I=. --java_out=. addressbook.proto
//生成对象
Person john =
Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("jdoe@example.com")
.addPhone(
Person.PhoneNumber.newBuilder()
.setNumber("555-4321")
.setType(Person.PhoneType.HOME))
.build();
System.out.println(john.toString());
//序列化为二进制数组
byte[] johnbyte = john.toByteArray();
//反序列化(中间过程你可以认为是经过了网络传输,文件存储等)
//注意对比两个System.out的输出
try {
Person john2 = Person.parseFrom(johnbyte);
System.out.println(john2.toString());
} catch (InvalidProtocolBufferException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
原文地址:http://blog.csdn.net/cheyiliu/article/details/44906665