json.Unmarshal 返回空白结构

json.Unmarshal returning blank structure

我有一个 JSON 看起来像这样的 blob

{
    "metadata":{
        "id":"2377f625-619b-4e20-90af-9a6cbfb80040",
        "from":"2014-12-30T07:23:42.000Z",
        "to":"2015-01-14T05:11:51.000Z",
        "entryCount":801,
        "size":821472,
        "deprecated":false
    },
    "status":[{
         "node_id":"de713614-be3d-4c39-a3f8-1154957e46a6",
         "status":"PUBLISHED"
    }]
}

我有一些代码可以将其转换回 go 结构

type Status struct {
    status string
    node_id string
}

type Meta struct {
    to string
    from string
    id string
    entryCount int64
    size int64
    depricated bool
}

type Mydata struct {
    met meta
    stat []status
}

var realdata Mydata
err1 := json.Unmarshal(data, &realdata)
if err1 != nil {
    fmt.Println("error:", err1)
}
fmt.Printf("%T: %+v\n", realdata, realdata)

但是我 运行 看到的只是一个归零结构

main.Mydata: {met:{to: from: id: entryCount:0 size:0 depricated:false} stat:[]}

我尝试先分配结构,但这也没有用,我不确定为什么它不产生值,也不返回错误

您的结构字段未导出。这是因为它们以小写字母开头。

EntryCount // <--- Exported
entryCount // <--- Not exported

当我说 "not exported" 时,我的意思是它们在您的包裹外是不可见的。您的包可以愉快地访问它们,因为它们在本地范围内。

至于 encoding/json 包 - 它看不到它们。您需要使所有字段都以大写字母开头,从而使 encoding/json 包可见,从而导出它们:

type Status struct {
    Status  string
    Node_id string
}

type Meta struct {
    To         string
    From       string
    Id         string
    EntryCount int64
    Size       int64
    Depricated bool
}

type Mydata struct {
    Metadata  Meta
    Status []Status
}

See it working on the Go Playground here

您还应该参考 Golang 规范以获得答案。具体来说,the part that talks about Exported Identifiers.