Reputation:
How to easily convert/parse the string representation of a JSON object into an instance of com.couchbase.client.java.document.json.JsonObject?
Upvotes: 2
Views: 5240
Reputation: 28351
edit, short answer: if you already have Json in String form I would just skip JsonObject and directly store the string via RawJsonDocument
instead. If you want to make use of JsonObject to read/write fields in the Json between obtaining the string and storing it, see
Flame113's answer (JsonTranscoder
).
In Couchbase Java SDK 2.x, JsonObject is the class used to work with JSON, in a simplified way. You can use it to construct well-formed JSON, with a limited sub-set of types allowed in like this:
JsonObject myJson = JsonObject.create()
.put("name", "bob")
.put("age", 23)
.put("role", "something");
Version 2.0.1 contains factory methods to create them from collections such as JsonObject.from(Map<String, ?>)
.
Note that RawJsonDocument allows you to store/retrieve some raw JSON as Strings. Support for String to JsonObject conversion via factory methods may come up in a future version, probably not before 2.1 though.
Upvotes: 3
Reputation: 90
You can use JsonTranscoder (API document) to do this.
String rawJson = "{\"companyname\":\"Apple\",\"employees\":[{\"name\":\"Steve\",\"age\":48},{\"name\":\"Michael\",\"age\":39}]}";
JsonTranscoder trans = new JsonTranscoder();
JsonObject jsonObj = trans.stringToJsonObject(rawJson);
Hope this help :)
Upvotes: 4