-
-
Save frestoinc/b200adb9cf02dc5208db30455821021f to your computer and use it in GitHub Desktop.
Gson interface adapter for "Register an InstanceCreator with Gson for this type may fix this problem"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object ConfigGson { | |
fun getGson() = GsonBuilder().apply { | |
registerTypeAdapter(Launchable::class.java, InterfaceAdapter<Launchable>()) | |
registerTypeAdapter(Trigger::class.java, InterfaceAdapter<Trigger>()) | |
}.create() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.* | |
import java.lang.reflect.Type | |
class InterfaceAdapter<T> : JsonSerializer<T>, JsonDeserializer<T> { | |
@Throws(JsonParseException::class) | |
override fun deserialize(jsonElement: JsonElement, type: Type, | |
jsonDeserializationContext: JsonDeserializationContext): T { | |
val jsonObject = jsonElement.asJsonObject | |
val prim = jsonObject.get(CLASSNAME) as JsonPrimitive | |
val className = prim.asString | |
val klass = getObjectClass(className) | |
return jsonDeserializationContext.deserialize(jsonObject.get(DATA), klass) | |
} | |
override fun serialize(src: T, type: Type?, jsonSerializationContext: JsonSerializationContext?): JsonElement { | |
val jsonObject = JsonObject() | |
val name: String = (src ?: Any())::class.java.name | |
jsonObject.addProperty(CLASSNAME, name) | |
jsonObject.add(DATA, jsonSerializationContext?.serialize(src)) | |
return jsonObject | |
} | |
/****** Helper method to get the className of the object to be deserialized */ | |
fun getObjectClass(className: String): Class<*> { | |
try { | |
return Class.forName(className) | |
} catch (e: ClassNotFoundException) { | |
throw JsonParseException(e.message) | |
} | |
} | |
companion object { | |
private val CLASSNAME = "CLASSNAME" | |
private val DATA = "DATA" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val string = ConfigGson.getGson().toJson(configData) | |
val configData = ConfigGson.getGson().fromJson(json, ConfigData::class.java) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment