douduan4116 2015-01-30 02:42
浏览 218
已采纳

json.Unmarshal返回空白结构

I have a JSON blob that looks like this

{
    "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

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
", 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

  • 写回答

1条回答 默认 最新

  • du2986 2015-01-30 02:50
    关注

    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. 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:

    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
    }
    

    <kbd>See it working on the Go Playground here</kbd>

    You should also reference the Golang specification for answers. Specifically, the part that talks about Exported Identifiers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!