【问题标题】:json.Unmarshal returning blank structurejson.Unmarshal 返回空白结构
【发布时间】:2015-03-29 11:40:12
【问题描述】:

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

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

【问题讨论】:

    标签: json go unmarshalling


    【解决方案1】:

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

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

    当我说“未导出”时,我的意思是它们在您的包裹之外不可见。您的包可以愉快地访问它们,因为它们的范围是本地的。

    至于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

    【讨论】:

    • 这不应该被否决,但您应该提及 json 标记值,以便为编组的 json 提供所需的名称。喜欢json:"entry_count"
    • 道歉。固定的。我是在工作中(我是 .NET 开发人员)进行大量代码讨论之后写的。
    • 我要对此表示赞成,因为它对我有帮助。但是,伙计,这让我脾气暴躁。
    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 2018-12-23
    • 2016-02-24
    • 2017-04-10
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多