Migrate JsonDeserializer from Java to Kotlin
Remove all null elements
filterNotNull
方法会把一个 nullable list 转成一个 non-null list,所以articleList 必须定义为nullable List
class ArticlesDeserializer @Inject constructor() : JsonDeserializer<List<Article>> {
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): List<Article> {
val jsonObject = json.asJsonObject
val type = object : TypeToken<ArrayList<Article>>() {}.type
val articleList = context.deserialize<List<Article?>>(jsonObject.get("rows"), type)
return articleList.filterNotNull()
}
}
Java codes:
// remove all null elements
articleList.removeAll(Collections.singleton(null));
通过注解抛出异常
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): List<Article> {
}
Java codes:
@Override
public List<Article> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
}
2018-08-27 Weiyi Li