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?
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:
This will give you a document that looks like:
If you want a different format, you can configure Jackson to serialize dates however you want.