使用Jackson方法readValue和HashMap的Kotlin中的问题

nle07wnf  于 7个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(60)

我尝试在Java中使用JacksonObjectMapper翻译这个函数:

public static HashMap<String, Serializable> jsonDecode(String body) {
    try {
        return new ObjectMapper().readValue(body, HashMap.class);
    } catch (IOException e) {
        return null;
    }
}

致Kotlin(此代码由IntelliJ IDEA提出):

fun jsonDecode(body: String?): java.util.HashMap<String, Serializable>? {
    return try {
        ObjectMapper().readValue(body, HashMap::class.java)
    } catch (e: IOException) {
        null
    }
}

但是编译器抛出一个错误:
类型不匹配:推断类型是HashMap<>!但是HashMap<String,Serializable>呢?预计

xlpyo6sf

xlpyo6sf1#

我试着这样做:

fun jsonDecode(body: String): java.util.HashMap<String, Serializable>? {
    val mapper = jacksonObjectMapper().registerModule(KotlinModule())
    val result: java.util.HashMap<String, Serializable> = mapper.readValue(body)
    return try {
        result
    } catch (e: IOException) {
        null
    }
}

相关问题