【问题标题】:Problems of Conversion of a List of HashMaps from/to JSON fails with Moshi 1.8.0 using Kotlin使用 Kotlin 的 Moshi 1.8.0 将 HashMaps 列表从/到 JSON 的转换问题失败
【发布时间】:2020-03-11 07:58:35
【问题描述】:

我看了很多例子,但没有帮助我解决我的问题, 我有这个与 JSON 进行映射的模型:

data class SomeResponse (
...
@Json(name = "dictionary")
var dictionary: HashMap<String, ArrayList<String>>? = null )

我正在使用 Moshi 与 JSON 进行转换,当转换过程开始时会发生异常

Platform java.util.HashMap>(没有注释)需要 要注册的显式 JsonAdapter

这是我的 Moshi 对象:

val customDateAdapter = object : Any() {
val dateFormat: DateFormat

init {
    dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH)
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"))
}

@ToJson
@Synchronized
fun dateToJson(d: Date): String {
    return dateFormat.format(d)
}

@FromJson
@Synchronized
fun dateToJson(s: String): Date {

    try {
        val date = dateFormat.parse(s)
        Timber.d("DATE_FORMATTER Did format: $date")
        return date
    } catch (e: ParseException) {

        try {
            val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH)
            df.timeZone = TimeZone.getTimeZone("GMT")
            return df.parse(s)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return Date()
    }
}

private val stringArrayListAdapter = object : Any() {

    @ToJson
    @Synchronized
    fun arrayListToJson(list: ArrayList<String>) : List<String> = list

    @FromJson
    @Synchronized
    fun arrayListFromJson(list: List<String>) : ArrayList<String> = ArrayList(list)
}

val moshi: Moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .add(customDateAdapter)
    .add(stringArrayListAdapter)
    .build()

如何解决这个问题

【问题讨论】:

    标签: java android kotlin retrofit moshi


    【解决方案1】:

    Moshi 仅支持Map。使用Map 或为HashMap 创建一个适配器。

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2021-04-24
      • 2022-07-28
      • 1970-01-01
      相关资源
      最近更新 更多