mongodbmongo-java-drivermongojack

How to insert Date object with the latest mongojack?


so in my object, I have private Date date; when I insert I got this exception:

Caused by: com.fasterxml.jackson.databind.JsonMappingException: JsonGenerator of type org.mongojack.internal.object.document.DocumentObjectGenerator not supported: org.mongojack.internal.DateSerializer is designed for use only with org.mongojack.internal.object.BsonObjectGenerator or org.mongojack.internal.stream.DBEncoderBsonGenerator or com.fasterxml.jackson.databind.util.TokenBuffer (through reference chain: com.test.DocumentWrapper["date"])

I am trying to set up the mongo TTL by using that date field.


Solution

  • I have had the same issue recently: to store date as Date object into MongoDB via MongoJack. First of all, I used MongoJack 2.10.0 version. And it requires to create own Serializer and Deserializer.

    public class Serializer extends JsonSerializer<DateTime> {
    
        @Override
        public void serialize(DateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeObject(new Date(value.getMillis()));
        }
    }
    
    public class Deserializer extends JsonDeserializer<DateTime> {
    
    private static final DateDeserializer DATE_DESERIALIZER = new DateDeserializer();
    
        @Override
        public DateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            Date date = DATE_DESERIALIZER.deserialize(p, ctxt);
            return date == null ? null : new DateTime(date);
        }
    }
    
    .....
    @JsonSerialize(using = Serializer.class)
    @JsonDeserialize(using = Deserializer.class)
    private DateTime testDate;
    
    public DateTime getTestDate() {
        return testDate;
    }
    
    public void setTestDate(DateTime testDate) {
        this.testDate = testDate;
    }
    ......
    

    In my case, I converted Date into joda DateTime to keep consistency with my code but it's possible to change to another type (LocalDateTime, OffsetDateTime, etc.)