Is Gson available in KMM? if not what would be the...
# multiplatform
s
Is Gson available in KMM? if not what would be the alternative of Gson, I used
Kotlin Serialization
but not giving alternative of
TypeToken
example use case is I wanted to convert below snippet completely into KMM specific by just using
kotlin.serialization
end up seeing
typeToken
not found
Copy code
fun <T : Any> getTypeListv(typeArgument: KClass<T>): KType? {
    return TypeToken.getParameterized(List::class, typeArgument).type
}
j
Just so I understand, whats the usecase of TypeToken? If I understand the question correct I think you only need that because of Gson, but not needed in kotlinx serialization.
s
@Joel Denke I Wanted to achieve this mapping... without gson
Copy code
fun <T : Any> listToJson(listObj: List<T>?, type: Class<T>): String? {
    return try {
        gson.toJson(listObj ?: listOf<T>(), getTypeList(type))
    } catch (e: JsonParseException) {
        PwLog.e("Parse Error (listToJson): Model Class :: $type", e)
        String.EMPTY
    }
}
Copy code
fun <T : Any> getTypeList(typeArgument: Class<T>): Type? {
    return TypeToken.getParameterized(List::class.java, typeArgument).type
}
m
Maybe something like this
Copy code
@OptIn(InternalSerializationApi::class)
fun <T : Any> getTypeSerializer(typeArgument: KClass<T>): KSerializer<T> {
    val elementSerializer = typeArgument.serializer()
    return elementSerializer
}
Usage example:
Copy code
val stringListSerializer = getTypeSerializer(String::class)
val stringList: List<String> = listOf("a", "b", "c")
val serializedStringList = Json.encodeToString(ListSerializer(stringListSerializer), stringList)
j
I dont think need anything extra, just do:
Copy code
val dataList = listOf(Data(42, "str"), Data(12, "test"))
val jsonList = Json.encodeToString(dataList)
As long as all objects in it is @Serializable, like Data in this sample.
m
@Suresh Maidaragi, @Joel Denke is correct, in
kotlinx.serialization
you don't need that method. My previous answer was a respond to the main question but now that we have more details on your need, we don't need that implementation.
👍 1
731 Views