typeAdapter = typeAdapter.nullSafe();
public static Gson getGson() { Gson gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create(); // Get the date adapter TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class); // Ensure the DateTypeAdapter is null safe TypeAdapter<Date> safeDateTypeAdapter = dateTypeAdapter.nullSafe(); // Build the definitive safe Gson instance return new GsonBuilder() .setDateFormat(DATE_FORMAT) .registerTypeAdapter(Date.class, safeDateTypeAdapter) .create(); }
@SuppressWarnings("unchecked") @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { TypeAdapter<T> adapter = null; Class<? super T> clazz = type.getRawType(); TypeAdapterFactory skipPast = this; if(TObject.class.isAssignableFrom(clazz)) { adapter = (TypeAdapter<T>) new TypeAdapter<TObject>() { @Override public TObject read(JsonReader in) throws IOException { return null; } @SuppressWarnings("rawtypes") @Override public void write(JsonWriter out, TObject value) throws IOException { // Convert to Java and use the converted type's // delegate for JSON serialization Object java = Convert.thriftToJava(value); TypeAdapter delegate = gson.getDelegateAdapter( skipPast, TypeToken.get(java.getClass())); delegate.write(out, java); } }; } if(adapter != null && nullSafe) { adapter = adapter.nullSafe(); } return adapter; }
adapter = adapter.nullSafe();
adapter = adapter.nullSafe();
typeAdapter = typeAdapter.nullSafe();