# Deserialize a JSON String to a Binary Tree

## A simple solution

We know that Jackson is very convenient to deserialize a JSON string into a ArrayList, HashMap or POJO object.

But how to deserialize a JSON String to a binary tree?

The definition of binary tree node is as follows:

The JSON String is as follows:

{
"value": 2,
"left": {
"value": 1,
"left": null,
"right": null
},
"right": {
"value": 10,
"left": {
"value": 5,
"left": null,
"right": null
},
"right": null
}
}


The above JSON string represents a binary tree as the following:

  2
/ \
1   10
/
5


The solution is quite simpler, since JSON can express tree naturally, Jackson can deal with recursive tree directly. Just annotate a constructor with JsonCreator:

Let’s write a unite test to try it:

## A compact serialization format

Well, there is a little problem here, the JSON string above is very verbose. Let’s use another kind of serialization format, i.e., serialize a binary tree in level order traversal. For example, the binary tree above can be serialized as the following JSON string:

[2,1,10,null,null,5]


Now how to deserialize this JSON string to a binary tree?

The idea is very similar to my previous article, Deserialize a JSON Array to a Singly Linked List. Just make the BinaryTreeNode implement java.util.list, pretend that it’s a list, write our own deserialization code so that Jackson can treat a binary tree as a list.

The complete code of BinaryTreeNode is as the following:

Then comes with the unit tests: