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.

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

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大