I hava a java node pojo :-
public class Node {
String name;
List<Node> children;
List<Object> values;
}
I am trying to convert this to json string.
Two approaches I have tried so far
Initially using simple gson.tojson was giving me OOM exception. Then I tried with this solution (Gson, serialize a tree structure) switched to TypeAdapter as below :-
public class NodeAdapter extends TypeAdapter<Node> {
@Override
public void write(JsonWriter jsonWriter, TreeNode node) throws IOException {
jsonWriter.beginObject()
.name("name")
.jsonValue("\"" + node.getName() + "\"")
.name("value")
.jsonValue("\"" + node.getValues() + "\"")
.name("children")
.beginArray();
// Recursive call to the children nodes
for (Node c : node.getChildren()) {
this.write(jsonWriter, c);
}
jsonWriter.endArray()
.endObject();
}
@Override
public Node read(JsonReader jsonReader) throws IOException {
return null;
}
}
Now this TypeAdapter approach works fine when the response is not too big, however, when the response starts to get bigger then it starts throwing OOM exception.
I am trying to convert Java object to json string like this :-
{
"record": [
{
"name" : "Path A",
"children" : [
{
"name": "Path B",
"children" : [
{
"name": "Path C",
"children" : [],
"values" : ["val5", "val6" ]
}
],
"values" : [
"val3", "val4"
]
}
],
"values" : [
"val1", "val2"
]
}
]
}
In above json, children can have n childs.
The other approach I looked for is json streaming, but could not find a solution for my problem statement yet.
Any help/suggestion would be highly appreciated.