2015-11-09 14 views
6

Ho cercato di creare una stringa JSON in Java utilizzando la libreria di Jackson (v.1.7.4, è l'unica che posso utilizzare per questo progetto) per formato accettato da jsTree (https://www.jstree.com/docs/json/). Mi interessa solo le proprietà "text" e "children". Il problema è che non sto ottenendo un metodo ricorsivo funzionante per farlo.Creazione ricorsiva di una stringa JSON su jsTree con Jackson

Se ho un semplice albero come questo:

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); 

I'd aspettano la mia stringa da:

{text: "root", children: [{text:"A", children:[{text:"C", children: []}]}, {text:"B", children: [{text: "D", children: []}, {text:"E", children:[]}]}] } 

sto cercando di costruire la stringa JSON utilizzando il modello Albero da Jackson. Il mio codice sembra così lontano qualcosa di simile:

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)); 
    } 

} 

ho provato un paio di varianti di questo, ma nessun successo finora. So che la risposta è probabilmente più semplice di quanto sto provando, ma sono bloccato. Forse la condizione di stop non è appropriata o la logica stessa (il mio pensiero è di provare e riutilizzare gli oggetti ObjectNode e ArrayNode alla prossima chiamata, per "inserire" l'elemento "children" (da json) sul prossimo nodo figlio sul albero, quindi sarebbe costruito all'indietro, ma alla fine ottengo variabili nulle).

mio albero e nodo lezioni si basano sui seguenti punti: http://sujitpal.blogspot.com.br/2006/05/java-data-structure-generic-tree.html

risposta

2

Non il migliore approccio, ma ottiene il lavoro fatto:

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)); 
    } 
} 
Problemi correlati