Go return struct as JSON in HTTP request

huangapple go评论85阅读模式
英文:

Go return struct as JSON in HTTP request

问题

我在Go中定义了以下结构体:

type repoStars struct {
    name 	string
    owner  	string
    stars	int
}

我创建了一个包含多个上述结构体项的数组repoItems := []repoStars{}

repoItems的样子如下所示:

Go return struct as JSON in HTTP request

我试图将这些项作为JSON响应返回:

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(repoItems)

但是它看起来是空的。

Go return struct as JSON in HTTP request

我在这里做错了什么?

英文:

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:

Go return struct as JSON in HTTP request

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

Go return struct as JSON in HTTP request

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
}

huangapple
  • 本文由 发表于 2023年1月18日 18:28:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75157782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定