Search code examples
javaandroidgson

Convert ArrayList<Custom> to gson in Java Android


Good afternoon. I can not understand why the code does not work after publishing in the Google market. Before publishing in android studio code

ArrayList<TableAccount> tableAccount = getTableAccount();
String jsonStr = new Gson().toJson(tableAccount);

result:

Log.d(TAG, "RESULT: " + jsonStr);
RESULT: [{"name":"payment","valueFloat":0.0,"valueInt":0,"valueStr":"no"}]

But, after posting, I see:

Log.d(TAG, "RESULT: " + jsonStr);
RESULT: [{"a":"payment","b":"no","c":0,"d":0.0}]

Why do the letters a b c appear?

And where do the keys disappear? ["name", "valueFloat", "valueInt", "valueStr"]


Solution

  • Apparently, you turned on ProGuard/R8 for your release build, and its obfuscation mode renamed your fields.

    The biggest lesson from here is to make sure that you test your release builds before uploading them to Google Play.

    To fix the problem, you could:

    • Turn off ProGuard/R8 entirely,
    • Leave it on but disable obfuscation entirely,
    • Leave it on but disable obfuscation for these specific classes, or
    • Use @SerializedName annotations to teach Gson what names to use, instead of its default of using Java reflection to look up the names of the fields (as obfuscation renames those fields)