如何忽略Json解析错误?

时间:2018-03-07 10:41:56

标签: android json retrofit

查询返回一个列表,但有时无法解析该列表中的对象。在这种情况下,我想返回null并返回带有null对象的列表。这该怎么做?现在我尝试创建自定义适配器

public class ServiceMenuItemAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (type.getRawType() != ServiceMenuItem.class) return null;

    TypeAdapter<ServiceMenuItem> defaultAdapter = (TypeAdapter<ServiceMenuItem>) gson.getDelegateAdapter(this, type);
    return (TypeAdapter<T>) new ServiceMenuItemAdapter(defaultAdapter);
}

private class ServiceMenuItemAdapter extends TypeAdapter<ServiceMenuItem> {

    protected TypeAdapter<ServiceMenuItem> defaultAdapter;


    public ServiceMenuItemAdapter(TypeAdapter<ServiceMenuItem> defaultAdapter) {
        this.defaultAdapter = defaultAdapter;
    }

    @Override
    public void write(JsonWriter out, ServiceMenuItem value) throws IOException {
        defaultAdapter.write(out, value);
    }

    @Override
    public ServiceMenuItem read(JsonReader in) throws IOException {
       try{
           return defaultAdapter.read(in);
       }
       catch(Exception e){
           return null
       }
    }

1 个答案:

答案 0 :(得分:0)

如果您想避免NullPointerException,最好使用optString()代替getString()

如果您是在任何时候从JSON获取数据,那么您可能拥有特定Key值的空数据,而不是实现Null条件,更好地利用此优化方法optString("<keyname>")