class Node{
private String id
private String parentId
private List<Node>children
public void addChildren(Node child){
getChildren().add(child)
}
public List<Node>getChildren()
public String transformTojson(Node node ,StringBuffer jsonStr){
//递归
if(jsonStr ==null){
StringBuffer jsonStr=new ()
}
if(node.id!=null){
//拼接父节点json串
jsonStr.append(id:node.id,children:#&children)
}
List childNodeList = node.getChildren()
StringBuffer childrenSB = new()
for( Node node :childNodeList){
childrenSB=transformTojson(node)
}
sonStr.replaceFirst("#&children",childrenSB)
return jsonStr
}
}
伪代码大概这样。
transformTojson方法可以不自己写,直接使用第三方工具jar包的json转化方法,比如gjson。
先递归出一个node对象,再将node对象转换成json串。直接进行字符串的json操作不建议。
class
Node{
private
String
id
private
String
parentId
private
List<Node>
children
public
void
addChildren(Node
child){
getChildren().add(child)
}
public
List<Node>
getChildren()
public
String
transformTojson(Node
node
,StringBuffer
jsonStr){
//递归
if(jsonStr
==null){
StringBuffer
jsonStr=new
()
}
if(node.id!=null){
//拼接父节点json串
jsonStr.append(id:node.id,children:#&children)
}
List
childNodeList
=
node.getChildren()
StringBuffer
childrenSB
=
new()
for(
Node
node
:childNodeList){
childrenSB=transformTojson(node)
}
sonStr.replaceFirst("#&children",childrenSB)
return
jsonStr
}
}
伪代码大概这样。
transformTojson方法可以不自己写,直接使用第三方工具jar包的json转化方法,比如gjson。