json.Unmarshal返回空白结构 [英] json.Unmarshal returning blank structure

查看:96
本文介绍了json.Unmarshal返回空白结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON blob,看起来像这样

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

至于 encoding / json 包虽然 - 它无法看到它们。你需要让所有的字段都对 c $ c> encoding / json 包可见,使它们都以大写字母开头,从而导出它们:

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
}

看到它在Go Playground上工作

您还应该参考Golang规范中的答案。具体来说,讨论导出标识符的部分

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

这篇关于json.Unmarshal返回空白结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆