其他分享
首页 > 其他分享> > android-Moshi适配器跳过列表中的不良对象

android-Moshi适配器跳过列表中的不良对象

作者:互联网

我使用Moshi,我需要使用越野车解决我的问题.有时,当我请求对象列表时,其中一些不包含必填字段.当然,我可以捕获并处理JsonDataException,但是我想跳过这些对象.我该如何与Moshi合作?

更新资料

我有几个完成任务的模型

@JsonClass(generateAdapter = true)
data class User(
        val name: String,
        val age: Int?
)

@JsonClass(generateAdapter = true)
data class UserList(val list: List<User>)

和错误的JSON

{
  "list": [
    {
      "name": "John",
      "age": 20
    },
    {
      "age": 18
    },
    {
      "name": "Jane",
      "age": 21
    }
  ]
}

如您所见,第二个对象没有必填名称字段,我想通过Moshi适配器跳过它.

解决方法:

看来我找到了答案

class SkipBadListObjectsAdapterFactory : JsonAdapter.Factory {
    override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<*>? {
        return if (annotations.isEmpty() && Types.getRawType(type) == List::class.java) {
            val elementType = Types.collectionElementType(type, List::class.java)
            val elementAdapter = moshi.adapter<Any>(elementType)

            SkipBadListObjectsAdapter(elementAdapter)
        } else {
            null
        }
    }

    private class SkipBadListObjectsAdapter<T : Any>(private val elementAdapter: JsonAdapter<T>) :
        JsonAdapter<List<T>>() {
        override fun fromJson(reader: JsonReader): List<T>? {
            val goodObjectsList = mutableListOf<T>()

            reader.beginArray()

            while (reader.hasNext()) {
                try {
                    elementAdapter.fromJson(reader)?.let(goodObjectsList::add)
                } catch (e: JsonDataException) {
                    // Skip bad element ;)
                }
            }

            reader.endArray()

            return goodObjectsList

        }

        override fun toJson(writer: JsonWriter, value: List<T>?) {
            throw UnsupportedOperationException("SkipBadListObjectsAdapter is only used to deserialize objects")
        }
    }
}

谢谢“来自其他主题的人” =)

标签:moshi,kotlin,adapter,json,android
来源: https://codeday.me/bug/20191211/2106935.html