首页 > 解决方案 > 为什么在 json.Unmarshal() 之后我得到一个空结构?

问题描述

编码器。我完全是新手,对 json.Unmarshal 输出有点困惑:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`

    var res []struct{}
    err := json.Unmarshal([]byte(s), &res)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(res)
}

输出:

[{} {} {}]

为什么是空的?你可以在这里试试:https: //play.golang.org/p/yztOLJADIXx

标签: go

解决方案


如果您想在不知道其字段的情况下解组 JSON 对象,请使用map[string]interface{}

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`

    var res []map[string]interface{}
    err := json.Unmarshal([]byte(s), &res)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(res)
}

在这里试试:https: //play.golang.org/p/iPlBgguE8Kk

但是,如果您知道要解组的字段的名称,则应该定义结构。在您的情况下,它看起来像这样:

type Person struct {
    First   string   `json:"First"`
    Last    string   `json:"Last"`
    Age     int      `json:"Age"`
    Sayings []string `json:"Sayings"`
}

在此处尝试此解决方案:https: //play.golang.org/p/jCrCteYTaIf


推荐阅读