此例用 微信的 设置菜单为例 底部三个菜单, 每个菜单里三个子菜单
定义结构体
type Btn struct{
Name string `json:"name"`
Type string `json:"type"`
Url string `json:"url"`
Sub_button []Btn `json:"sub_button,omitempty"` //值为空时 直接忽略
}
type menu struct{
Button []Btn `json:"button"`
}
结构体赋值
jsonData := Menu{
Button:[]Btn{
{Name:"home",Type:"view",Url:"https://www.qq.com/auth"},
{Name:"tool",Sub_button:[]Btn{
{Name:"a1",Type:"view",Url:"https://www.qq.com/a1"},
{Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
{Name:"a3",Type:"view",Url:"https://www.qq.com/a3"},
}},
{Name:"other",Sub_button:[]Btn{
{Name:"a1",Type:"view",Url:"https://www.qq.com/a1"},
{Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
{Name:"a3",Type:"view",Url:"https://www.qq.com/a3"},
}},
},
}
结构体转json
str,err := json.Marshal(jsonData)
if err != nil{
panic(err)
}
fmt.println(string(str))
golang 模拟请求时, 传的参数是 map[string]interface{}
的类型, 所以这里需要将json数据处理成这种格式
param := map[string]interface{}{
"button":[]Btn{
{Name:"home",Type:"view",Url:"https://www.qq.com/auth"},
{Name:"tool",Sub_button:[]Btn{
{Name:"a1",Type:"view",Url:"https://www.qq.com/1"},
{Name:"a1",Type:"view",Url:"https://www.qq.com/1"},
{Name:"a1",Type:"view",Url:"https://www.qq.com/1"},
}},
{Name:"other",Sub_button:[]Btn{
{Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
{Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
{Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
}},
},
}
*结构体命名需要大写 才会导出到json串中, 可以通过 struct tag 设置导出的别名, 可以通过 omitempty 忽略值为空的字段
有疑问加站长微信联系(非本文作者)