Last active
August 17, 2023 16:09
-
-
Save BobbyESP/be7e9272880b9a3d7e2c7e1ca8e9a6ec to your computer and use it in GitHub Desktop.
Type converter generator for Room entities (data classes)
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 java.io.File | |
import kotlin.reflect.KClass | |
fun main() { | |
val classesToGenerate = emptyList() //Create a list with your classes || Example: listOf(Agent::class, Ability::class, Buddy::class, Bundle::class) | |
for (clazz in classesToGenerate) { | |
generateTypeConverter(clazz) | |
} | |
} | |
fun generateTypeConverter(clazz: KClass<*>) { | |
val packageName = clazz.java.`package`?.name | |
val className = clazz.simpleName | |
val typeConverterClassName = "${className}TypeConverters" | |
val typeConverter = """ | |
package $packageName; | |
import androidx.room.TypeConverter; | |
import kotlinx.serialization.decodeFromString; | |
import kotlinx.serialization.encodeToString; | |
import kotlinx.serialization.json.Json; | |
class $typeConverterClassName { | |
val json = Json { | |
ignoreUnknownKeys = true | |
encodeDefaults = true | |
}; | |
@TypeConverter | |
fun fromJson(jsonString: String): ${clazz.qualifiedName} { | |
return json.decodeFromString(jsonString); | |
} | |
@TypeConverter | |
fun toJson(value: ${clazz.qualifiedName}): String { | |
return json.encodeToString(value); | |
} | |
@TypeConverter | |
fun fromJsonList(jsonString: String): List<${clazz.qualifiedName}> { | |
return json.decodeFromString(jsonString); | |
} | |
@TypeConverter | |
fun toJsonList(value: List<${clazz.qualifiedName}>): String { | |
return json.encodeToString(value); | |
} | |
} | |
""".trimIndent() | |
val outputFile = File("library/src/main/java/converters/${packageName?.replace('.', '/')}/$typeConverterClassName.kt") | |
outputFile.parentFile?.mkdirs() | |
outputFile.writeText(typeConverter) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment