Java – Deserialize an array of JSON objects to the root object in Java?

Deserialize an array of JSON objects to the root object in Java?… here is a solution to the problem.

Deserialize an array of JSON objects to the root object in Java?

My goal is to deserialize the BSON document array on Android. Deserialization fails when the outer array is anonymous (attempt to deserialize to CustomObject[].class). When an array is wrapped in an object whose key contains the array, it works (deserialized to WrapperObject.class).

In JSON, the object looks like this:

[{"id":....},{"id":....},{"id":....} ....]

According to BSON Specification A BSON array is a regular BSON document with a key value of an integer. In other words, the same object in BSON looks like this:

{"0":{"id":....},"1":{"id":....},"2":{"id":....} ....}

I’m trying to deserialize the above using bson4jackson, but it throws a “unable to deserialize instance of x from START_OBJECT token” error, and in the stack trace I notice that the unexpected token is “0” – BSON representation at the beginning of the array.

Currently, my solution is to wrap the array in a new root object, and in JSON it looks like this:

{"data":[{"id":....},{"id":....},{"id":....},....]}

Can you set up bson4jackson or any other Java deserialization library to treat the root object as an array and treat it as-is, without line breaking?

Solution

The reason is that bson4jackson is a low-level library that does not know the type of object that is currently being resolved. In BSON arrays are objects, bson4jackson just assumes that each document has an object as its root.

However, there is a workaround. Whenever reading an array, Jackson calls the low-level parser’s isExpectedStartArrayToken() method. So if the current object is a document, but bson4jackson can switch to array parsing, but needs an array.

The fix has just been implemented. For details, see:
https://github.com/michel-kraemer/bson4jackson/issues/31

Related Problems and Solutions