问题描述
我有一个像这样的 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"
}]
}
我有一些代码可以将其转换回 go 结构
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
推荐答案
您的结构字段未导出.这是因为它们以小写字母开头.
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
包 - 它看不到它们.您需要使所有字段都以大写字母开头,从而使 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
}
您还应该参考 Golang 规范以获取答案.具体来说,讨论导出标识符的部分.
You should also reference the Golang specification for answers. Specifically, the part that talks about Exported Identifiers.
这篇关于json.Unmarshal 返回空白结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!