Home>

Convert the instance of any class to Json format,
I want to implement a method that returns the Json format string to the instance.
I could implement it in java, but I can't write it in kotlin and am asking a question.

Source that worked in java
/ **
 * Convert the instance to a character string and save.
 * /
public void setObject (String key, Object object) {
    Gson gson = new Gson ();
    setValue (key, gson.toJson (object));// There is another value setting method. gson.toJson converts Object to string
}
/ **
 * Return the stored value to the instance.
 * /
public<T>T getObject (String key, Class<T>classOfT) {
    Gson gson = new Gson ();
    return gson.fromJson (getString (key), classOfT);// Get Json format character with getString
}
What I tried with kotlin
/ **
 * Save [any] in [key].
 * /
fun setAny (key: String, any: Any) {
    setValue (key, Gson (). toJson (any)) // I heard that Object is Any in kotlin, so Any. I think this is correct.
}
/ **
 * For the time being, there is no compiler error.
 * /
fun<T>getAny (kiSpKey: KiSpKey, classOfT: Class<T>): T (
    return Gson (). fromJson (getString (kiSpKey), classOfT)
}
/ **
 * Caller
 * /
getAny ("test", arbitrary class name.class) // compile error (Not enough information to infer type variable T)

I don't know which is wrong, how to call it or how to define the getAny method.
Please point out.

  • Answer # 1

    You're passing the class wrong. Kotlin hasArbitrary class name.classThere is no notation. I think that the build will pass if you get and pass the Java class as follows. Document

    getAny ("test", any class name :: class.java)

    In addition, it can be described more easily by using Kotlin's qualified modifier.

    inline fun<reified T>getAny (kiSpKey: KiSpKey): T {
        return Gson (). fromJson (getString (kiSpKey), T :: class.java)
    }
    // call example
    getAny  ("test")