6
我一直在试图建立一个JSON字符串在Java中使用杰克逊库(v.1.7.4,这是我可以用于该项目的唯一一个)到格式由jsTree接受(https://www.jstree.com/docs/json/)。我只关心“文字”和“儿童”的属性。问题是,我没有得到一个工作的递归方法来做到这一点。递归构建一个JSON字符串与jsTree与杰克逊
如果我有一个简单的树像这样的:
Tree<String> tree = new Tree<String>();
Node<String> rootNode = new Node<String>("root");
Node<String> nodeA = new Node<String>("A");
Node<String> nodeB = new Node<String>("B");
Node<String> nodeC = new Node<String>("C");
Node<String> nodeD = new Node<String>("D");
Node<String> nodeE = new Node<String>("E");
rootNode.addChild(nodeA);
rootNode.addChild(nodeB);
nodeA.addChild(nodeC);
nodeB.addChild(nodeD);
nodeB.addChild(nodeE);
tree.setRootElement(rootNode);
我倒是希望我的字符串是:
{text: "root", children: [{text:"A", children:[{text:"C", children: []}]}, {text:"B", children: [{text: "D", children: []}, {text:"E", children:[]}]}] }
我正尝试建立使用树模型的JSON字符串来自杰克逊。我的代码到目前为止看起来像这样:
public String generateJSONfromTree(Tree<String> tree) throws IOException{
String json = "";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = new JsonFactory();
ByteArrayOutputStream out = new ByteArrayOutputStream(); // buffer to write to string later
JsonGenerator generator = factory.createJsonGenerator(out, JsonEncoding.UTF8);
JsonNode rootNode = mapper.createObjectNode();
JsonNode coreNode = mapper.createObjectNode();
JsonNode dataNode = (ArrayNode)generateJSON(tree.getRootElement()); // the tree nodes
// assembly arrays and objects
((ObjectNode)coreNode).put("data", dataNode);
((ObjectNode)rootNode).put("core", coreNode);
mapper.writeTree(generator, rootNode);
json = out.toString();
return json;
}
public ArrayNode generateJSON(Node<String> node, ObjectNode obN, ArrayNode arrN){
// stop condition ?
if(node.getChildren().isEmpty()){
arrN.add(obN);
return arrN;
}
obN.put("text", node.getData());
for (Node<String> child : node.getChildren()){
// recursively call on child nodes passing the current object node
obN.put("children", generateJSON(child, obN, arrN));
}
}
我尝试了一些变化,但迄今没有成功。我知道答案可能比我尝试的更简单,但我被卡住了。也许停止条件不合适或逻辑本身(我的想法是在下一次调用时尝试重用ObjectNode和ArrayNode对象,以便将“children”元素(来自json)插入到下一个子节点上树,所以它会倒退,但最终我得到空变量)。
我的树和节点类是基于以下几点:http://sujitpal.blogspot.com.br/2006/05/java-data-structure-generic-tree.html