结构体嵌套 树形结构 json字符串与结构体相互转换

 

package main

import (
	"encoding/json"
)

type T struct {
	K        int32
	V        string
	Children []T
}

func convert() {
	var target T
	err := json.Unmarshal([]byte(jsonStr), &target)
	if err != nil {
		panic(err)
	}

	bs, err := json.Marshal(jsonStruct)
	if err != nil {
		panic(err)
	}
	s := string(bs)
	if s != "" {

	}
}

var jsonStr = `
{
    "K": 1,
    "V": "v",
    "Children": [
        {
            "K": 11,
            "V": "11v",
            "Children": [
                {
                    "K": 111,
                    "V": "111v",
                    "Children": []
                },
                {
                    "K": 112,
                    "V": "112v",
                    "Children": [
                        {
                            "K": 1121,
                            "V": "1121v",
                            "Children": []
                        },
                        {
                            "K": 1122,
                            "V": "1122v",
                            "Children": []
                        }
                    ]
                }
            ]
        },
        {
            "K": 12,
            "V": "12v",
            "Children": []
        }
    ]
}
`

var jsonStruct = T{
	K: 1,
	V: "v",
	Children: []T{
		{
			K: 11,
			V: "11v",
			Children: []T{
				{
					K:        111,
					V:        "111v",
					Children: []T{},
				},
				{
					K: 112,
					V: "112v",
					Children: []T{
						{
							K:        1121,
							V:        "1121v",
							Children: []T{},
						},
						{
							K:        1122,
							V:        "1122v",
							Children: []T{},
						},
					},
				},
			},
		},
		{
			K:        12,
			V:        "12v",
			Children: []T{},
		},
	},
}

  

 

posted @ 2022-03-07 10:08  papering  阅读(112)  评论(0编辑  收藏  举报