英文:
Go return struct as JSON in HTTP request
问题
我在Go
中定义了以下结构体:
type repoStars struct {
name string
owner string
stars int
}
我创建了一个包含多个上述结构体项的数组repoItems := []repoStars{}
。
repoItems
的样子如下所示:
我试图将这些项作为JSON响应返回:
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(repoItems)
但是它看起来是空的。
我在这里做错了什么?
英文:
I've defined the following struct in Go
:
> type repoStars struct {
name string
owner string
stars int
}
And I've created an array repoItems := []repoStars{}
which has multiple items of the struct above.
This is how repoItems
looks like:
I'm trying to return those items as a JSON response:
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(repoItems)
And it seems empty
What am I doing wrong here?
答案1
得分: 2
如果结构字段以小写字母开头,表示它们是未导出的。所有未导出的字段都不会被编码器序列化。
将其改为首字母大写。
type RepoStars struct {
Name string
Owner string
Stars int
}
英文:
If the struct fields start with a lower case letter it means unexported. All unexported fields won't be serialised by the encoder.
Change it to capital first letter.
type repoStars struct {
Name string
Owner string
Stars int
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论