引入ProtoBuf
根目录build.gradle添加
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.8'
模块build.gradle添加
plugins {
id 'com.google.protobuf'
}
android {
sourceSets {
main {
proto {
srcDir 'src/main/proto' //指定.proto文件路径
}
}
}
}
// 添加ProtoBuf插件
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.5.1'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.builtins {
java {}// 生产java源码
}
}
}
}
dependencies {
// 引入ProtoBuf依赖库
implementation 'com.google.protobuf:protobuf-java:3.5.1'
implementation 'com.google.protobuf:protoc:3.5.1'
}
新建proto文件
在src/main/proto目录下新建test.proto
syntax = "proto3";
option java_package = "com.test";
option java_outer_classname = "TestProto";
message Person {
int32 id = 1;
string name = 2;
string email = 3;
}
使用ProtoBuf序列化和反序列化
val test = TestProto.Person.newBuilder()
test.setEmail("asdsd@sdads").setId(2).setName("test123").build()
val data = test.build().toByteArray()
Log.i("ProtoBuf","${String(data)}")
val test1 = TestProto.Person.parseFrom(data)
Log.i("ProtoBuf","${test1}")
日志打印:
I/ProtoBuf:test123asdsd@sdads
I/ProtoBuf: id: 2
name: "test123"
email: "asdsd@sdads"