json.Unmarshal 返回空白结构

标签 json go unmarshalling

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

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

最佳答案

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

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

您还应该引用 Golang 规范以获得答案。具体来说,the part that talks about Exported Identifiers .

关于json.Unmarshal 返回空白结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28228393/

相关文章:

linux - Go 中的服务器没有监听 tun0

android - 包裹解码未知类型代码

scala - 如何在客户端调用中使用 akka-http-circe?

c# - 配置管理器无法获取 ASP.net 5 中的连接字符串

java - 在不需要现有类的情况下在 java 中创建 JSON 文字

java - 我无法从 servlet 到 jsp 获取 json 对象。我能怎么做?

go - ElasticSearch 上特定搜索类型的分页

go - 从数据库中保存和读取 Golang 中的 byte[]

json - 嵌套结构的解码字段不起作用

javascript - NSDictionary 类型的 React Native JSON 值无法转换为 NSString