简体   繁体   English

json.Unmarshal返回空白结构

[英]json.Unmarshal returning blank structure

I have a JSON blob that looks like this 我有一个看起来像这样的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"
    }]
}

and I have a little code to transform that back into go structs 我有一些代码将其转换回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)

but what I see when I run this is just a zeroed structure 但是我在运行时看到的只是一个零位结构

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

I tried allocating the struct first but that also didn't work, I'm not sure why its not producing values, and its not returning an error 我尝试先分配该结构,但这也没有用,我不确定为什么它不产生值,并且不返回错误

Your struct fields are not exported. 您的结构字段不会导出。 This is because they start with a lowercase letter. 这是因为它们以小写字母开头。

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

When I say "not exported", I mean they are not visible outside of your package. 当我说“未导出”时,是指它们在您的包装之外不可见。 Your package can happily access them because they are scoped locally to it. 您的软件包可以愉快地访问它们,因为它们在本地作用域内。

As for the encoding/json package though - it cannot see them. 至于encoding/json包-它看不到它们。 You need to make all of your fields visible to the encoding/json package by making them all start with an uppercase letter, thereby exporting them: 您需要通过将所有字段都以大写字母开头,从而导出它们,从而使所有字段对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 在这里查看它在Go Playground上的运行情况

You should also reference the Golang specification for answers. 您还应该参考Golang规范以获得答案。 Specifically, the part that talks about Exported Identifiers . 具体来说, 是有关导出标识符的部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM