How do you control how the Couchbase Java client serializes Dates?

755 views Asked by At

Here's my code (Couchbase Java SDK 3)

Cluster cluster = Cluster.connect("localhost", "Administrator", "password");
Collection c = cluster.bucket("default").defaultCollection();
c.upsert("myDocumentId", new Date());

When I look at the resulting document in Couchbase, I see the java.util.Date has been converted to epoch milliseconds:

1602791214674

What I want instead is for the date to be formatted like yyyy-mm-dd.

How can I make that happen?

1

There are 1 answers

0
dnault On

By default, the Couchbase Java client uses Jackson to serialize and deserialize JSON. Unless you tell it otherwise, it will use an ObjectMapper with default settings. By default, Jackson serializes java.util.Date objects by converting them to milliseconds since the epoch.

You have a couple of choices. If you're using a POJO to represent your document content, you can apply Jackson annotations to the date fields to control how they are [de]serialized. Here's an article that shows how to use the @JsonFormat annotation to control how a date field is serialized.

Alternatively, you can configure an ObjectMapper to change the default way dates are serialized. Here's how you tell the Couchbase Java SDK to use your custom ObjectMapper:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

ClusterEnvironment env = ClusterEnvironment.builder()
    .jsonSerializer(JacksonJsonSerializer.create(objectMapper))
    .build();

Cluster cluster = Cluster.connect("localhost",
    ClusterOptions.clusterOptions("Administrator", "password")
        .environment(env));

Collection c = cluster.bucket("default").defaultCollection();
c.upsert("myDocumentId", new Date());

cluster.disconnect();

// since we created a custom environment, we're responsible for shutting it down
env.shutdown();

This will give you a document that looks like:

"2020-10-15T19:59:45.685+0000"

If you want a different format, you can configure Jackson to serialize dates however you want.