GSON解析輔助

默認的Gson解析有時不能滿足業務的需求,可能需要設置對Gson進行一些配置

.addConverterFactory(GsonConverterFactory.create(new Gson()))

可以在配置Gson轉換時傳入我們另行配置的Gson
比如我們想要對所有的解析異常都不報錯,而是設置爲null。

public final class SafeTypeAdapterFactory implements TypeAdapterFactory{  

        @Override  
        public  TypeAdapter create(Gson gson, final TypeToken type) {  
            final TypeAdapter delegate = gson.getDelegateAdapter(this,type);  
            return new TypeAdapter() {  
                @Override  
                public void write(JsonWriter out, T value) throws IOException {  
                    try {  
                        delegate.write(out, value);  
                    } catch (IOException e) {  
                        delegate.write(out, null);  
                    }  
                }  

                @Override  
                public T read(JsonReader in) throws IOException {  
                    try {  
                        return delegate.read(in);  
                    } catch (IOException e) {  
                        in.skipValue();  
                        return null;  
                    } catch (IllegalStateException e) {  
                        in.skipValue();  
                        return null;  
                    } catch (JsonSyntaxException e) {  
                        in.skipValue();  
                        if(type.getType() instanceof Class){  
                            try {  
                                return (T) ((Class)type.getType()).newInstance();  
                            } catch (Exception e1) {  

                            }  
                        }  
                        return null;  
                    }  
                }  
            };  
        }  
    }
Gson myGson = new GsonBuilder().registerTypeAdapterFactory(new SafeTypeAdapterFactory()).create();

作者:汪汪一隻貓
鏈接:http://www.imooc.com/article/78804
來源:慕課網

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章