我正在嘗試開發一個代表網站頁面之間鏈接的小程序。 我想通過一個關係來表示每個鏈接,並且每個頁面由一個節點來表示。將圖形數據轉換爲Json
現在我使用了一個小數據集,它的樣子:
HOME -> PAGE 1 -> PAGE 3 -> PAGE 5
-> PAGE 2 -> PAGE 4
將我所有的節點和關係後,我要遍歷以JSON我圖形和打印數據有類似:
{
"name": "HOME",
"children": [
{
"name": "PAGE 1",
"children": [
{
"name": "PAGE 3",
"children": [
{"name": "PAGE 5"}
]
},
{
"name": "PAGE 2",
"children": [
{"name": "PAGE 4"}
]
}
]
}
]
}
有沒有這樣做的功能,或者我必須自己寫json?
這裏是我的代碼:
private static void routing(final GraphDatabaseService graphDb)
{
Transaction tx = graphDb.beginTx();
Page home, p1, p2, p3, p4, p5;
try
{
home = new Page(graphDb, "http://www.site.com/");
p1 = new Page(graphDb, "http://www.site.com/page1.html");
p2 = new Page(graphDb, "http://www.site.com/page2.html");
p3 = new Page(graphDb, "http://www.site.com/page3.html");
p4 = new Page(graphDb, "http://www.site.com/page4.html");
p5 = new Page(graphDb, "http://www.site.com/page5.html");
home.createLinkTo(p1);
home.createLinkTo(p2);
p1.createLinkTo(p3);
p2.createLinkTo(p4);
p3.createLinkTo(p5);
tx.success();
tx = graphDb.beginTx();
final TraversalDescription linkTraversal = Traversal.description().depthFirst().relationships(RelationshipTypes.LINK);
String output = "";
for (Node node : linkTraversal.traverse(home.getUnderlyingNode()).nodes())
{
output += node.getProperty("url") + "\n";
}
System.out.println(output);
}
finally
{
tx.finish();
}
}
Page類
public class Page implements Serializable{
private static final long serialVersionUID = 1L;
static final String URL = "url";
private final Node underlyingNode;
private List<Page> children = null;
public Page(final Node node)
{
this.underlyingNode = node;
}
public Page(final GraphDatabaseService graphDb, final String url)
{
this.underlyingNode = graphDb.createNode();
underlyingNode.setProperty(URL, url);
children = new ArrayList<Page>();
}
public Node getUnderlyingNode()
{
return underlyingNode;
}
public String getUrl()
{
return (String) underlyingNode.getProperty(URL);
}
public void createLinkTo(final Page other)
{
Relationship link = underlyingNode.createRelationshipTo(other.underlyingNode, RelationshipTypes.LINK);
children.add(other);
//link.setProperty(ANCHOR, 'Mon ancre');
}
@Override
public String toString()
{
return "Page [url=" + getUrl() + "]";
}
我更喜歡用JSON來表示一個圖表,只需列出節點和邊界即可。每個節點都有一個唯一的id(可能是其內部的Neo id),並且邊只是簡單地表示爲起始節點id和末端節點id。使用任何基本的Java JSON庫和Neo中的'GlobalGraphOperations'類,您應該可以使用少量代碼構建此JSON消息。 – rmlan