小编典典

json.Unmarshal返回空白结构

go

我有一个看起来像这样的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:[]}

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


阅读 569

收藏
2020-07-02

共1个答案

小编典典

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

EntryCount // <--- Exported
entryCount // <--- 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](http://play.golang.org/p/adZgg_x4j3)

您还应该参考Golang规范以获得答案。具体来说,是有关导出的标识符的部分

2020-07-02