0

I wanna create generic method for convert json string to List of objects.

fun  convertJsonStringToObjectList(jsonString: String , clazz: Class<Any>) :List<Any>{
        val gson = Gson()
        val objectList = gson.fromJson(jsonString, Array<clazz>::class.java).asList()
        return objectList
}

This code does not works. I know how to convert json string to a class like this:

 fun <T> convertJsonStringToObject(jsonString: String, clazz: Class<T>): T {
        val gson = Gson()
        val objectList = gson.fromJson(jsonString, clazz)
        return objectList
    }

The problem is i wan to get class type from method and then add Array type to it and get classtype again. I do not know how to handle this.

1 Answer 1

1

Because of the type erasure and the special reflection types of arrays in jvm, you cannot do this really clean but there is a way using reified keyword in kotlin in which it is possible:

inline fun <reified T> convertJsonStringToObject(jsonString: String): Array<T> =
    Gson().fromJson(jsonString, emptyArray<T>().javaClass)

(You may notice that I have used emptyArray<T> to get the type instead of Array<T>::class.java. Because the latter one will give you an Object[] not an Array<T>. This may be a bug in kotlin.)

(it may look appropriate here but is not sufficient for complicated cases, because we have made it inline.)

Also, here are two alternative methods:

Passing the array type to the function (like java):

fun <T> convertJsonStringToObject(
    jsonString: String, 
    clazz: Class<Array<T>>): Array<T> =
    Gson().fromJson(jsonString, clazz)

//and call it like this:
val result = convertJsonStringToObject(
    "[{\"test\":123}, {\"test\": 456}]", 
    Array<Test>::class.java)

Parsing the json array manually one by one:

fun <T> convertJsonStringToObjectList(
    jsonString: String, 
    clazz: Class<T>): List<T> {
    val gson = Gson()
    val objects = gson.fromJson(jsonString, JsonElement::class.java).asJsonArray
    return objects.map { gson.fromJson(it, clazz) }
}

(again you can omit the clazz param using reified)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.