I wrote a small library module, and I'm trying to consume some JSON data. However, GSON is not serializing the data. It's not throwing any errors. Everything is just null. Further, if I move the same code out of the library and into my app (in this case I just put it in App.kt) then it works.
Why wouldn't GSON serialize when in a Library Module? Is there something else I need to do?
In the library module
data class MyMessage(@SerializedName("message") val message: String?)
object MessageCenter {
private const val TAG = "MessageCenter"
init {
val json = "{\"message\":\"A custom message\"}"
Log.d(TAG, "JSON RAW $json")
val mm: MyMessage = Gson().fromJson(json, MyMessage::class.java)
Log.d(TAG, "MyMessage: ${mm.message}")
}
fun start(){
Log.i(TAG, "Message Center Started")
}
}
build.gradle
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
In my App
class App : Application() {
override fun onCreate() {
super.onCreate()
MessageCenter.start()
}
}
build.gradle The App also needs Gson for other libraries. So it is also found in the app's module build.gradle.
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
implementation project(':messagecenter')
}
D/MessageCenter: JSON RAW {"message":"A custom message"} D/MessageCenter: MyMessage: null I/MessageCenter: Message Center Started
If I bring the code and data class out of the library and into my main app then GSON works:
data class MyMessage(@SerializedName("message") val message: String?)
class App : Application() {
override fun onCreate() {
super.onCreate()
MessageCenter.start()
val json = "{\"message\":\"A custom message\"}"
Log.d("App.kt", "JSON RAW $json")
val mm: MyMessage = Gson().fromJson(json, MyMessage::class.java)
Log.d("App.kt", "MyMessage: ${mm.message}")
}
}
D/MessageCenter: JSON RAW {"message":"A custom message"} D/MessageCenter: MyMessage: null I/MessageCenter: Message Center Started
D/App.kt: JSON RAW {"message":"A custom message"} D/App.kt: MyMessage: A custom message
Here is my progaurd-rules for my library:
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-dontwarn sun.misc.**
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.mycompany.messagecenter.data.* { <fields>; }
# Prevent proguard from stripping interface information from TypeAdapter, TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapter
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
# Prevent R8 from leaving Data object members always null
-keepclassmembers,allowobfuscation class * {
@com.google.gson.annotations.SerializedName <fields>;
}