这个json的Unmarshal怎么不对啊,问题在哪?

代码如下: 错误提示是cannot unmarshal object into Go value of type []main.Menus,怎么改这哪个struct呢?

package main
import (
    "encoding/json"
    "fmt"
)

func main() {

    var jsonBlob = []byte(`{
    "menu":"结构管理",
    "submenu":[
        {
            "item":"站点管理",
            "url":"/site/siteList.jsp",
            "domain":"domain"
        },
        {
            "item":"频道管理",
            "url":"./channel/channelList.jsp",
            "domain":"domain"
        }
    ],
    "menu":"内容管理",
    "submenu":[
        {
            "item":"文档管理",
            "url":"/article/articleList.jsp",
            "domain":"domain"
        },
        {
            "item":"审核发布",
            "url":"/article/publish.jsp",
            "domain":"domain"
        }
    ],
    "menu":"发布管理",
    "submenu":[
        {
            "item":"缓存管理",
            "url":"/cache/cache_manage.jsp",
            "domain":"domain"
        },
        {
            "item":"内容篡改恢复",
            "url":"/publish/juggleList.jsp",
            "domain":"domain"
        }
    ]
}`)

type SubMenu struct {

    Item   string  
    Url    string  
    Domain string  
}

    type Menus struct {
    menu    string     
    submenu []SubMenu
    }

    var mu []Menus
    err := json.Unmarshal(jsonBlob, &mu)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Printf("%+v", mu)
}

共 6 个回复


jimmykuu

你这个json对么?

# 0

dxhdxh2k

json应该是正确的,在http://www.ij2ee.com/bejson/bejson.html上校验过。

# 1

jimmykuu

校验完不就剩这点了么:

{
    "menu": "发布管理",
    "submenu": [
        {
            "item": "缓存管理",
            "url": "/cache/cache_manage.jsp",
            "domain": "domain"
        },
        {
            "item": "内容篡改恢复",
            "url": "/publish/juggleList.jsp",
            "domain": "domain"
        }
    ]
}
# 2

dxhdxh2k

如果用校验完的,也是同样的提示啊。

# 3

jimmykuu

首先,你这个json不是个数组,所以不应该定义为数组,应该是var mu Menus

其次Menus里面的字段应该大写,小写是不可见的,

type Menus struct {
    Menu    string     
    Submenu []SubMenu
}
# 4

liuhaochuan

type xxxx struct {
    Menu string `json:"menu"`
    Submenu []struct {
        Item string `json:"item"`
        URL string `json:"url"`
        Domain string `json:"domain"`
    } `json:"submenu"`
}
# 5