Hi all,
I am using Couchbase Java Client 2.0.1 to interact with Couchbase server 3.0.1.
I have noticed that the toString() method of Couchbase JsonObject does not escape special characters (escape sequences) of string values - resulting in an invalid Json string that cannot be serialized back to a Json object (using Jackson for instance).
Document example (as viewed through Couchbase UI)-
{
"data": {
"source1": {
"description": "test description \n blabla"
}
},
"id": 1234556
}
And here is my piece of code -
...
JsonDocument doc = bucket.get(key);
JsonObject content = getDocument(key).content();
String strObj = content.toString();
Map<String,Object> jsonObj = jacksonMapper.readValue(strObj, Map.class);
...
As a result strObj value is -
'{"data":{"source1":{"description": "test description \n blabla"}},"id": 1234556}'
Instead of being -
'{"data":{"source1":{"description": "test description \\n blabla"}},"id": 1234556}'
Making jacksonMapper.readValue() fail and throw the following exception -
com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value
Just for the reference, here is the toString() method of Couchbase JsonObject -
/**
* Converts the {@link JsonObject} into its JSON string representation.
*
* @return the JSON string representing this {@link JsonObject}.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
int size = content.size();
int item = 0;
for(Map.Entry<String, Object> entry : content.entrySet()) {
sb.append("\"").append(entry.getKey()).append("\":");
if (entry.getValue() instanceof String) {
sb.append("\"").append(entry.getValue()).append("\"");
} else {
if (entry.getValue() == null) {
sb.append("null");
} else {
sb.append(entry.getValue().toString());
}
}
if (++item < size) {
sb.append(",");
}
}
sb.append("}");
return sb.toString();
}
Note that special characters are not being escaped in the following line of code (taken from the toString method) -
...
sb.append("\"").append(entry.getValue()).append("\"");
...
By the way, this is how I indexed the document into Couchbase in the first place -
public RawJsonDocument updateDocument(String key, Map<String,Object> content)
{
RawJsonDocument doc = RawJsonDocument.create(key, jacksonMapper.writeValueAsString(content));
return bucket.upsert(doc);
}
What is your opinion about it?
Am I doing something wrong?
Is it a bug?
Thanks!!
Ronen.