美文网首页
自定义gson解析,避免解析错误,程序报错

自定义gson解析,避免解析错误,程序报错

作者: happyhou | 来源:发表于2020-04-17 15:47 被阅读0次

第一步注册
    val gson: Gson
        get() {
            return GsonBuilder(
                     .registerTypeAdapter(User::class.java, deserialize())
                    .registerTypeAdapter(object : TypeToken<RealmList<com.cityfruit.old.module.messages.StringObject>>() {}.type,StringObjectDeserializer())
//                    .registerTypeAdapter(RealmList::class.java, StringObjectDeserializer())
                    .registerTypeAdapter(Date::class.java, DateDeserializer())
                    .serializeNulls()
                    .create()
        
注册自定义的customList<customBean>

    public class StringObjectDeserializer : JsonDeserializer<RealmList<StringObject>> {

        @Throws(JsonParseException::class)
        override fun deserialize(json: JsonElement, typeOF: Type,
                                 context: JsonDeserializationContext): RealmList<StringObject>? {

            val valueType = (typeOF as ParameterizedType).getActualTypeArguments().get(0)
            var sss:RealmList<StringObject> = RealmList<StringObject>()
            try {

                for (item in json.asJsonArray) {
                    item?.let {
                        sss.add(context.deserialize(it,valueType))
                    }
                }

                return sss
            } catch (e: Exception) {
                return null
            }

            throw JsonParseException("Unparseable RealmList: \"" + json.asString
                    + "\". Supported formats: " )


        }
    
定义通用list

I want it ot work for every kind of list, like CustomList<Integer>, CustomList<String>, CustomList<CustomModel> not just a specific kind of list

class CustomListConverter implements JsonDeserializer<CustomList<?>> {
    public CustomList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
        Type valueType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];

        CustomList<Object> list = new CustomList<Object>();
        for (JsonElement item : json.getAsJsonArray()) {
            list.add(ctx.deserialize(item, valueType));
        }
        return list;
    }
普通的bean
public class User
{
    int id;
    String name;
    Timestamp updateDate;
}
@Override
public User deserialize(JsonElement json, Type type,
        JsonDeserializationContext context) throws JsonParseException {

    JsonObject jobject = json.getAsJsonObject();

    return new User(
            jobject.get("id").getAsInt(), 
            jobject.get("name").getAsString(), 
            new Timestamp(jobject.get("update_date").getAsLong()));
}

相关文章

网友评论

      本文标题:自定义gson解析,避免解析错误,程序报错

      本文链接:https://www.haomeiwen.com/subject/wblyvhtx.html