我正在尝试开发一个代表网站页面之间链接的小程序。 我希望通过关系表示每个链接,并通过节点表示每个页面。
现在我正在使用一些小数据集,它看起来像:
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 class of class class
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() + "]";
}
答案 0 :(得分:3)
假设你有一个代表你网页的bean,就像这样:
public class Page implements Serializable {
private String name;
private List<Page> children;
private transient GraphDatabaseService dbService;
// Constructors, Getters/Setters
}
您可以使用各种JSON库(例如Jackson或GSON)轻松地对其进行序列化。这是杰克逊的一个简单例子:
final Page home ; // Initialize and construct the home page
final ObjectMapper mapper = new ObjectMapper();
final String json = mapper.writeValueAsString(home);
答案 1 :(得分:0)
我认为最有效的格式类似于节点和边缘列表,有关CSV版本请参阅https://github.com/jexp/batch-import,D3在Javascript中执行类似操作,请参阅使用JSON读取的D3示例。
/彼得