我想把protobuf (由grpc生成)转换成JSON。
我知道在使用protobuf时,你可以使用:JSonFormat ( https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/JsonFormat ),但protobuf-lite ( implementation 'com.google.protobuf:protobuf-lite:3.0.0' )中并没有包含它,它是在安卓protobuf-gradle-plugin ( https://github.com/google/protobuf-gradle-plugin/issues/276 )中使用的。
还有别的选择吗?
我使用Kotlin,但是因为从grpc生成的协议是用java编写的,所以我不能使用Kotlin ( https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/runtime_usage.md#protobuf )的序列化。
有什么想法吗?
谢谢
发布于 2019-10-10 16:44:37
好的,我想我把它弄好了,这是我得到的解决方案,如果有人像我一样堆叠:
// GRPC
implementation "io.grpc:grpc-okhttp:${grpcVersion}" // CURRENT_GRPC_VERSION
implementation "io.grpc:grpc-stub:${grpcVersion}" // CURRENT_GRPC_VERSION
implementation "io.grpc:grpc-protobuf:$grpcVersion"
// Protobuf
implementation "com.google.protobuf:protobuf-java:$protobufVersion"
implementation "com.google.protobuf:protobuf-java-util:$protobufVersion"
protobuf {
protoc { artifact = "com.google.protobuf:protoc:$protobufVersion" }
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}" // CURRENT_GRPC_VERSION
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
java { }
}
task.plugins {
grpc { }
}
}
}
}现在我可以使用JsonFormat了:
val jsonPrinter = JsonFormat.printer().includingDefaultValueFields()
return jsonPrinter.print(myProtobufObject)资料来源:
https://github.com/google/protobuf-gradle-plugin#protos-in-dependencies https://github.com/grpc/grpc-java https://github.com/protocolbuffers/protobuf/tree/master/java
不幸的是,此解决方案与比Android Oreo更旧的解决方案不兼容:
https://github.com/protocolbuffers/protobuf/issues/6718
任何更新:
https://groups.google.com/forum/#!topic/protobuf/EC2TtPixCFY
https://stackoverflow.com/questions/58289920
复制相似问题