我有一个看起来像的json结构

{
"devices": [
    {
        "server": {
            "bu": {
                "add_info": false,
                "applications": [
                    [
                        "Systems",
                        12
                    ],
                    [
                        "SomeProject",
                        106
                    ]
                ],
                "name": [
                    [
                        "SomeName",
                        4
                    ],
                    [
                        "CommonName",
                        57
                    ]
                ],
                "owners": [
                    "SomeOwner1",
                    "SomeOwner2"
                ],
                "users": [
                    "SomeUser1",
                    "SomeUser2"
                ]
            }
        }
    }
  ]
}

我正在尝试将其添加到结构中,该结构看起来像
type TwoD [][]string
type MainContainer struct {
    Devices []struct{
        Server struct{
            Bu struct{
                Add_info string `json:"add_info"`
                Applications TwoD `json:"applications"`
                Name TwoD `json:"name"`
                Owners []string `json:"owners"`
                Users []string `json:"users"`
               } `json:"bu"`
               } `json:"server"`
    } `json:"devices"`
}

但是,当我打印结构时,我从2D slice 中仅获得一个值,而没有其他值。
func main() {
jsonfile, err  := ioutil.ReadFile("./search.json")
if err != nil {
    fmt.Println(err)
    os.Exit(1)
}
var jsonobject MainContainer
json.Unmarshal(jsonfile, &jsonobject)
fmt.Printf("%v", jsonobject)
}
{[{{{ [[Systems ]] [] [] []}}}]}
但是如果我在结构中省略了二维 slice
type MainContainer struct {
Devices []struct{
        Server struct{
            Bu struct{
                Add_info string `json:"add_info"`
                //Applications TwoD `json:"applications"`
                //Name TwoD `json:"name"`
                Owners []string `json:"owners"`
                Users []string `json:"users"`
               } `json:"bu"`
               } `json:"server"`
    } `json:"devices"`
}

一切都打印为
{[{{{ [SomeOwner1 SomeOwner2] [SomeUser1 SomeUser2]}}}]}
有人可以帮我找出问题所在吗?

Here是带有struct和sample json的golang游乐场的链接。此处的结构中注释了两个TwoD slice 。

注::编辑了带有未注释的2d slice 的运动场链接,以便可以注意到差异,并将类型字符串更改为bool,如@cnicutar所指出的,谢谢。

最佳答案

主要问题是您没有处理json.Unmarshal返回的错误。处理完该问题后,您的json(和解码结构)问题就变得显而易见。

if err := json.Unmarshal(jsonfile, &jsonobject); err != nil {
    fmt.Printf("Unmarshal: %v\n", err)
}

第一的:



因此Add_info应该是bool。修复并取消注释Applications之后:



将12更改为“12”,将106更改为“106”后,结果为:
{[{{{false [[Systems 12] [SomeProject 106]] [SomeUser1 SomeUser2]}}}]}

关于json - 嵌套JSON解码与二维 slice 成结构无法在golang中工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37499114/

10-12 07:25