Skip to content

Instantly share code, notes, and snippets.

@sc0rch
Last active July 9, 2016 01:48
Show Gist options
  • Save sc0rch/f49ffd0403816b74eea930590d76126c to your computer and use it in GitHub Desktop.
Save sc0rch/f49ffd0403816b74eea930590d76126c to your computer and use it in GitHub Desktop.
It's a part of Cheat Sheet for common Dagger 2 modules.
/**
* Created by sc0rch on 30.06.16.
* GSON module for Dagger 2.
*/
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Date;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import ru.your.project.BuildConfig;
@Module
public class GsonModule {
@Provides
@Singleton
public Gson provideGson(GsonUtcDateAdapter utcDateAdapter) {
GsonBuilder gsonBuilder = new GsonBuilder()
.registerTypeAdapter(Date.class, utcDateAdapter);
if (BuildConfig.DEBUG) {
gsonBuilder.setPrettyPrinting();
}
return gsonBuilder.create();
}
@Provides
@Singleton
public GsonUtcDateAdapter provideGsonUtcDateAdapter() {
return new GsonUtcDateAdapter();
}
}
/**
* Created by sc0rch on 30.06.16.
* GSON Adapter for Date-type.
*/
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Date;
public class GsonUtcDateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
// Only one locale in example, extend this gist to cover your needs.
public static final DateFormat DATE_ISO_8601_FORMAT = new SimpleDateFormat(DATE_ISO_8601, Locale.US);
@Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(DATE_ISO_8601_FORMAT.format(date));
}
@Override
public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return DATE_ISO_8601_FORMAT.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment