Reputation: 213
How to easily convert/parse the Java Object into a JSON object that is a instance com.couchbase.client.java.document.json.JsonObject?
I tried to do this:
import com.couchbase.client.deps.com.fasterxml.jackson.annotation.JsonProperty;
public class MyClass {
@JsonProperty("filed")
private String filed;
public MyClass(String filed) {
this.filed = filed;
}
public String getFiled() {
return filed;
}
and run this lines with imports:
import com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper;
import com.couchbase.client.java.document.json.JsonObject;
ObjectMapper mapper = new ObjectMapper();
MyClass test = new MyClass("a");
JsonObject node = mapper.convertValue(test, JsonObject.class);
and I get:
java.lang.IllegalArgumentException: Unrecognized field "filed" (class com.couchbase.client.java.document.json.JsonObject), not marked as ignorable (one known property: "names"])
at [Source: N/A; line: -1, column: -1] (through reference chain: com.couchbase.client.java.document.json.JsonObject["filed"])
at com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:2759)
at com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:2685)
Upvotes: 4
Views: 6756
Reputation: 637
I made a very simple library on top of the Java 2.x Couchbase Client which allows to perform CRUD operations synchronously, as well as asynchronously (through RxJava).
It shows how to use Jackson to serialize / deserialize the beans stored on Couchbase.
The project on GitHub: https://github.com/jloisel/reactive-couchbase
Upvotes: 0
Reputation: 28301
the JsonObject
in Couchbase is meant as a very basic API to work with JSON, close to a Map
: you put
simple values to it, you getString
, getInt
, etc... from it.
Note that only a limited set of types are accepted in a JsonObject: null, String, Integer, Long, Double, Boolean, JsonObject or JsonArray.
If you want to store domain objects, for now the best supported way is to marshal them to JSON strings (using your prefered flavor of Jackson, GSon, etc...) and store and retrieve them using the RawJsonDocument
.
Example to get a JSON string from the database:
RawJsonDocument doc = bucket.get("myKey", RawJsonDocument.class);
String jsonValue = doc.content();
MyClass value = unmarshalToMyClass(jsonValue); //this calls eg. Jackson
edit: the trick below doesn't work that great (eg. problem converting longs)
but here's a trick to do what you want to do: there's a preconfigured Jackson ObjectMapper
that you can use in JacksonTransformers.MAPPER
!
Upvotes: 6