定义proto文件
syntax = "proto3";
//输出的java文件包名
option java_package = "com.example.domain";
// 输出的java文件名
option java_outer_classname = "Pb";
message Person {
string name = 1;
int32 age = 2;
string address = 3;
}
编译
protoc--java_out=. .\student.proto
引入依赖
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.25.0</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
<version>3.25.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.protobuf-java-format</groupId>
<artifactId>protobuf-java-format</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.36</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
序列化与反序列化:
@Test
public void test3(){
Pb.Person.Builder p1 = Pb.Person.newBuilder();
p1.setAddress("北京")
.setAge(23)
.setName("zhang san").build();
System.out.println(p1.toString());
//序列化
Pb.Person build = p1.build();
//转换成字节数组
byte[] s = build.toByteArray();
System.out.println("protobuf数据bytes[]:" + Arrays.toString(s));
System.out.println("protobuf序列化大小: " + s.length);
try {
Pb.Person person = Pb.Person.parseFrom(s);
String jsonStr = JSONObject.toJSONString(person);
System.out.println("Json格式化结果:\n" + jsonStr);
System.out.println("Json格式化数据大小: " + jsonStr.getBytes().length);
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
}
结果如下
name: "zhang san"
age: 23
address: "\345\214\227\344\272\254"
protobuf数据bytes[]:[10, 9, 122, 104, 97, 110, 103, 32, 115, 97, 110, 16, 23, 26, 6, -27, -116, -105, -28, -70, -84]
protobuf序列化大小: 21
Json格式化结果:
{"address":"北京","age":23,"name":"zhang san"}
Json格式化数据大小: 48
参考连接: https://blog.csdn.net/wxw1997a/article/details/116755542
网友评论