Skip to content

Instantly share code, notes, and snippets.

@aarengee
Created April 21, 2020 08:48
Show Gist options
  • Save aarengee/e3ea670f64497b9140358a7db8077a24 to your computer and use it in GitHub Desktop.
Save aarengee/e3ea670f64497b9140358a7db8077a24 to your computer and use it in GitHub Desktop.
Serialization Deserilization thread safety issue resolved by using FastDateFormat in Google's GSON
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 org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Date;
public class DateTimeSerializer implements JsonSerializer<Date>, JsonDeserializer<Date> {
private String dateFormat;
public DateTimeSerializer(String dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(DateFormatUtils.format(date, dateFormat));// uses FastDateFormat singleton
}
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return DateUtils.parseDate(json.getAsString(), dateFormat);
} catch (ParseException e) {
return null;
}
}
}
public class MyClass {
private static Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateTimeSerializer("yyyy-MM-dd HH:mm:ss"))// any format is fine
.registerTypeAdapter(java.sql.Date.class, new DateTimeSerializer("yyyy-MM-dd HH:mm:ss"))
.create();
public static String foo_serialize(Object bar) {
return gson.toJson(bar);
}
public static Bar foo_deserialize(String bar) {
return gson.fromJson(bar,Bar.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment