环境配置:
< ProjectName>/build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.17'
}
}
< ProjectName>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
-
protobuf-lite以来方式
-
version3.8以前
dependencies {
implementation 'com.google.protobuf:protobuf-lite:3.0.0'
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.7.0'
}
plugins {
javalite {
artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.plugins {
javalite { }
}
}
}
}
-
version3.8以后 dependencies {
implementation 'com.google.protobuf:protobuf-javalite:3.8.0'
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.8.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option "lite"
}
}
}
}
}
-
protobuf-java方式
dependencies {
implementation 'com.google.protobuf:protobuf-java:3.17.3'
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.17.3'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.plugins {
java {}
}
}
}
}
注意事项:
-
protocol buffer 需要使用最新版本,否则可能会出现编译错误 -
protobuf-java是完整版本,protobuf-lite是轻量版本,轻量版本里面只有基本类型,没有google/protobuf/any.proto 文件 -
protocol buffer数据格式使用的话最好双方统一为该数据格式,否则一方面使用protocol buffer,一方面使用json或者xml的话,需要使用额外的数据格式转换库(比如protobuf-java-format)。但是这种方式会比较麻烦而且要兼容一些额外的操作,比如Any的范型 -
在使用json和protocol buffer进行转换的时候,如果在测试的时候需要注意不能使用单引号’。例如以下两种方式在单纯的解析时候可以使用,但是单引号那种在protocol buffer就不可以使用 第一种转义符使用: val json = "{\"code\":\"3\"}"
第二种单引号使用(错误示范): val json = "{'code':'3'}"
参考链接:
- Android 中使用Protocol Buffer
https://blog.csdn.net/qq_35599978/article/details/80386356
- 查看protocol buffer最新版本
https://github.com/google/protobuf-gradle-plugin
- Protocol Buffer
https://developers.google.com/protocol-buffers/docs/proto3
- Protocol Buffer在Java上的使用
https://developers.google.com/protocol-buffers/docs/javatutorial
-
Protocol Buffer在网络数据传输中的使用 https://blog.csdn.net/weixin_32757449/article/details/114093565 -
protobuf与json相互转换的方法 https://www.cnblogs.com/pcheng/p/9586039.html -
protobuf-java-format https://github.com/bivas/protobuf-java-format
|