Search code examples
jsonkotlinprotocol-buffers

Convert protobuf to JSON in Kotlin


Is there some easy way to convert protobuf message into JSON when using Kotlin? I have found multiple ways using JsonFormat in Java but this package does not seem to be available in Kotlin.

val myProto = MyProto.newBuilder().setId("id").build()
val json: String = ???

Solution

  • Perform like this:

        val myProto = MyProto.newBuilder().setId("id").build()
        val json: String = JsonFormat.printer().print(myProto)
    
        println(json)
    

    Ensure you have the protobuf and protobuf-java-util dependencies

        implementation("com.google.protobuf:protobuf-java:3.21.12")
        implementation("com.google.protobuf:protobuf-java-util:3.21.12")
    

    Do check the version of the dependencies. It was working in mine.