Skip to content

Instantly share code, notes, and snippets.

@xhanin
Created June 10, 2015 09:59
Show Gist options
  • Save xhanin/4ae02c985a4b6290ed2d to your computer and use it in GitHub Desktop.
Save xhanin/4ae02c985a4b6290ed2d to your computer and use it in GitHub Desktop.
RESTX issue 204 workaround
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import de.undercouch.bson4jackson.BsonGenerator;
import de.undercouch.bson4jackson.serializers.BsonSerializer;
import java.io.IOException;
import java.time.Instant;
import java.util.Date;
public class BsonJSR310Module extends SimpleModule {
public BsonJSR310Module() {
super("BsonJSR310Module");
addSerializer(Instant.class, new BsonSerializer<Instant>() {
@Override
public void serialize(Instant date, BsonGenerator bsonGenerator, SerializerProvider serializerProvider)
throws IOException {
if (date == null) {
serializerProvider.defaultSerializeNull(bsonGenerator);
} else {
bsonGenerator.writeDateTime(new Date(date.toEpochMilli()));
}
}
});
addDeserializer(Instant.class, new JsonDeserializer<Instant>() {
@Override
public Instant deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Date date = (Date) jp.getEmbeddedObject();
return Instant.ofEpochMilli(date.getTime());
}
});
}
}
import org.jongo.Mapper;
import org.jongo.marshall.jackson.JacksonMapper;
import restx.factory.Module;
import restx.factory.Provides;
import restx.jackson.BsonJodaTimeModule;
import restx.jackson.Views;
import javax.inject.Named;
@Module(priority = -10)
public class Java8Module {
@Provides
@Named("Mapper")
public Mapper mapper() {
return new JacksonMapper.Builder()
.registerModule(new BsonJodaTimeModule()) // to keep compatibility with joda time
.registerModule(new BsonJSR310Module())
.withView(Views.Private.class)
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment