Home > Net >  Gson: toJson/toJsonTree minifyEnabled issue
Gson: toJson/toJsonTree minifyEnabled issue

Time:09-05

I am trying to convert an kotlin object to JsonString using Gson.

I am using these functions to convert object to string

Gson().toJson(object) Gson().toJsonTree(object)

If minifyEnabled is false, it is working fine

If minifyEnabled is true, it is converting to something like {'a': '', 'b': ''}

Keys are replaced with a,b,c,d... etc

Tried with adding Gson proguard. But couldn't find any luck

Could anyone help me out of this issue

CodePudding user response:

The issue is not with Gson being affected by ProGuard/R8. The issue is that your code is being affected by ProGuard/R8.

Suppose that this is the Kotlin class that you are trying to convert to/from JSON:

data class Thingy(
  val firstBitOfData: String,
  val secondBitOfData: String
)

By default, Gson uses Java reflection to decide how to convert the object to JSON. So, for example, if we had:

val myThingy = Thingy("foo", "bar")
val jsonOfThingy = Gson().toJson(myThingy)

println(jsonOfThingy)

That will give us something like:

{"firstBitOfData": "foo", "secondBitOfData: "bar"}

Gson asks Java/Kotlin "hey, what is the name of these properties?", and it uses those by default when it generates the JSON. However, ProGuard/R8 changes the names of those properties. That is why you wind up with the JSON that you do in your question.

You have three main options for affecting this behavior.

First, you could turn off ProGuard/R8 for this class (and any other classes that you want to convert to/from JSON), by updating your ProGuard/R8 rules file.

Second, you could turn ProGuard/R8 renaming entirely for the app, so it minifies but does not change names of things, via -dontobfuscate.

Third, you could use the SerializedName annotation to tell Gson to avoid using reflection and instead use the names that you specify:

data class Thingy(
  @SerializedName("firstBitOfData") val firstBitOfData: String,
  @SerializedName("secondBitOfData") val secondBitOfData: String
)

(with this, it does not matter what ProGuard/R8 does in terms of changing the names of the properties)

  • Related