【问题标题】:Recursively building a JSON string to jsTree with Jackson使用 Jackson 将 JSON 字符串递归构建到 jsTree
【发布时间】:2016-02-10 14:20:15
【问题描述】:

我一直在尝试使用 Jackson 库(v.1.7.4,这是我可以用于此项目的唯一一个)在 Java 中构建一个 JSON 字符串,以 jsTree 接受的格式 (https://www.jstree.com/docs/json/) .我只关心“文本”和“儿童”属性。问题是,我没有得到一个可行的递归方法来做到这一点。

如果我有一棵像这样的简单树:

    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:[]}]}] }

我正在尝试使用 Jackson 的树模型构建 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 对象,以在下一个子节点上“插入”“子”元素(来自 json)树,所以它会向后构建,但最后我得到空变量)。

我的树和节点类基于以下内容:http://sujitpal.blogspot.com.br/2006/05/java-data-structure-generic-tree.html

【问题讨论】:

    标签: java json recursion jackson jstree


    【解决方案1】:

    不是最好的方法,但它可以完成工作:

    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.util.Iterator;
    
    import com.fasterxml.jackson.core.JsonEncoding;
    import com.fasterxml.jackson.core.JsonFactory;
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.node.ArrayNode;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    
    public class TreeApp {
    
        public String generateJSONfromTree(Tree<String> tree) throws IOException {
            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);
    
            ObjectNode rootNode = generateJSON(tree.getRootElement(), mapper.createObjectNode());
            mapper.writeTree(generator, rootNode);
    
            return out.toString();
        }
    
        public ObjectNode generateJSON(Node<String> node, ObjectNode obN) {
            if (node == null) {
                return obN;
            }
    
            obN.put("text", node.getData());
    
            ArrayNode childN = obN.arrayNode();
            obN.set("children", childN);        
            if (node.getChildren() == null || node.getChildren().isEmpty()) {
                return obN;
            }
    
            Iterator<Node<String>> it = node.getChildren().iterator();
            while (it.hasNext()) {  
                childN.add(generateJSON(it.next(), new ObjectMapper().createObjectNode()));
            }
            return obN;
        }
    
        public static void main(String[] args) throws IOException {
            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);
    
            System.out.println(new TreeApp().generateJSONfromTree(tree));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 2020-09-04
      • 2014-01-01
      • 2019-12-21
      • 2013-05-09
      • 2019-06-03
      • 2017-07-27
      相关资源
      最近更新 更多