package main
import(
//"encoding/json"
"encoding/json"
"fmt"
)
type Datanode struct {
Id int `json:"id"`
PId int `json:"pid"`
Name string `json:"name"`
Child []*Datanode `json:"child"`
}
var Jsondata []byte //存储json数据
func main(){
Data := make([]Datanode, 0) //存储所有初始化struct
var a Datanode
a.Id = 0
a.PId = -1
a.Name = "目录"
Data = append(Data,a)
a.Id = 1
a.PId = 0
a.Name = "一、水果"
Data = append(Data,a)
a.Id = 2
a.PId = 1
a.Name = "1.苹果"
Data = append(Data,a)
a.Id = 3
a.PId = 1
a.Name = "2.香蕉"
Data = append(Data,a)
a.Id = 4
a.PId = 0
a.Name = "二、蔬菜"
Data = append(Data,a)
a.Id = 5
a.PId = 4
a.Name = "1.芹菜"
Data = append(Data,a)
a.Id = 6
a.PId = 4
a.Name = "2.黄瓜"
Data = append(Data,a)
a.Id = 7
a.PId = 6
a.Name = "(1)黄瓜特点"
Data = append(Data,a)
a.Id = 8
a.PId = 4
a.Name = "3.西红柿"
Data = append(Data,a)
a.Id = 9
a.PId = 0
a.Name = "三、关系"
Data = append(Data,a)
var data []*Datanode
data = make([]*Datanode,0)
for i,_ := range Data{
var a *Datanode
a = &Data[i]
data = append(data, a)
}
node := &Data[4] //父节点
maketree(data,node) //调用生成tree
transformjson(node) //转化为json
jsontotree(Jsondata) //json 转为struct
}
func maketree(Data []*Datanode, node *Datanode){ //参数为父节点,添加父节点的子节点指针切片
childs,_ :=havechild(Data,node) //判断节点是否有子节点并返回
if childs != nil{
fmt.Printf("\n")
fmt.Println(*node)
fmt.Println("子节点:")
for _ ,v:= range childs{
fmt.Println(*v)
} //打印
node.Child = append(node.Child,childs[0:]...) //添加子节点
for _,v := range childs{ //查询子节点的子节点,并添加到子节点
_, has := havechild(Data,v)
if has {
maketree(Data, v) //递归添加节点
}
}
}
}
func havechild(Data []*Datanode, node *Datanode)(child []*Datanode,yes bool){
for _,v := range Data{
if v.PId == node.Id {
child = append(child, v)
}
}
if child != nil {
yes = true
}
return
}
func transformjson(Data *Datanode){ //转为json
Jsondata,_ = json.Marshal(Data)
fmt.Println(string(Jsondata))
}
func jsontotree(jsondata []byte){ //json转struct
var a Datanode
err := json.Unmarshal(jsondata,&a)
fmt.Println("22222222222222",string(jsondata))
if err != nil{
fmt.Println(err)
}else{
fmt.Println(a.Id,a.PId,a.Name)
for _,v := range a.Child{
fmt.Println(*v)
}
}
}
有疑问加站长微信联系(非本文作者)