syntax = "proto2";
option java_package = "com.zht.protobuf";
option java_outer_classname = "UserModel";
message User{
required int32 id = 1;
required string username = 2;
required string password = 3;
optional string email = 4;
}
3.使用protoc.exe命令生成实体
protoc.exe -I [proto文件所在目录] --java_out [JAVA类存放目录] [proto文件绝对路径]
4.将实体放入工程进行实体的构造和赋值
将实体放入工程:
构造并且赋值:
public class Main {
public static void main(String[] args) throws InvalidProtocolBufferException {
//获取构造器并进行赋值
UserModel.User.Builder builder = UserModel.User.newBuilder();
builder.setId(1);
builder.setUsername("zhuanght");
builder.setPassword("123456");
builder.setEmail("aiuzht119@163.com");
//获取实体
UserModel.User user = builder.build();
System.out.println("源数据:\r"+ user.toString());
System.out.println("序列化后:"+Arrays.toString(user.toByteArray()));
//模拟接收Byte[],反序列化成User实体
byte[] data =user.toByteArray();
User u = User.parseFrom(data);
System.out.println("\r解析:\r" +u.toString());
}
}
打印结果 :
源数据:
id: 1
username: "zhuanght"
password: "123456"
email: "aiuzht119@163.com"
序列化后:[8, 1, 18, 8, 122, 104, 117, 97, 110, 103, 104, 116, 26, 6, 49, 50, 51, 52, 53, 54, 34, 17, 97, 105, 117, 122, 104, 116, 49, 49, 57, 64, 49, 54, 51, 46, 99, 111, 109]
解析:
id: 1
username: "zhuanght"
password: "123456"
email: "aiuzht119@163.com"
5.获取序列化后的字节数组在网络中进行传输