Go Json Marshal字段不输出

问题

json.Marshal默认不输出非导出的字段

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Test struct {
	Total int    `json:"total"`
	item  string `json:"item"`
}

func main() {
	resp := Test{
		Total: 1,
		item:  "aa",
	}
	body, err := json.Marshal(resp)
	fmt.Printf("body=%v, err=%v \n", string(body), err) // 输出 body={"total":1}, err=<nil>
}

解决方式

把字段改成大写字母开头

updatedupdated2023-12-062023-12-06