2

With Couchbase's jsonObject we can create object with certain fields:

import    com.couchbase.client.java.document.json.JsonObject
...
JsonObject content = JsonObject.create().put("some", "value");

The put function has several String & value options such as double, int, String etc, as can be seen here.

I was looking for a way to put a whole object in it. Something like:

Cat cat = new Cat(.....)
JsonObject content = JsonObject.create().put(cat);

Is there a way to do it and not to iterate over all of Cat's fields?

riorio
  • 6,500
  • 7
  • 47
  • 100

1 Answers1

3

So here is how it can be done:

Cat cat = new Cat(...);
String asJson = gson.toJson(cat);
JsonObject.fromJson(asJson);
riorio
  • 6,500
  • 7
  • 47
  • 100
  • Yup! Another neat trick is that with SDK 3, you might not need to use JsonObject at all. SDK 3 supports data binding; you can call `collection.upsert("felix", cat)`, and the SDK will use the `JsonSerializer` configured on the `ClusterEnvironment` to convert `cat` to JSON. The default serializer uses a repackaged version of Jackson; that's good enough for simple binding, but if you want to get serious, you can bring your own version of Jackson. If you prefer Gson, you could write your own `JsonSerializer` that delegates to Gson. – dnault Jun 21 '23 at 18:31