gpt4 book ai didi

go - c.JSON gin.H{()} 输出空对象

转载 作者:行者123 更新时间:2023-12-01 22:08:23 25 4
gpt4 key购买 nike

我刚开始结合 Gin 框架学习 GO(lang),我决定编写一些简单的 api 来获取有关酒精饮料的数据。

我当前的问题是 api(http://localhost:8080/alcohol-drinks 上的 get 方法)返回空数据对象

我的代码:

package main

import (
"github.com/gin-gonic/gin"
)

type alcoholDrink struct {
name string
description string
nutritionsAmount string
nutritions map[string]string
}

func main() {
r := gin.Default()
r.GET("/alcohol-drinks", func(c *gin.Context) {

d := []alcoholDrink{
{
name: "Gin",
description: "DescriptionGin is a distilled alcoholic drink that derives its predominant flavour from juniper berries. Gin is one of the broadest categories of spirits, all of various origins, styles, and flavour profiles, that revolve around juniper as a common ingredient",
nutritionsAmount: "per 100 grams",
nutritions: map[string]string{
"Calories": "263",
"TotalFat": "0 g",
"Cholesterol": "0 mg",
"Sodium": "2 mg",
"Carbohydrate": "0 g",
"Protein": "0 g",
},
},
{
name: "Vodka",
description: "odka is a clear distilled alcoholic beverage with different varieties originating in Poland and Russia. It is composed primarily of water and ethanol, but sometimes with traces of impurities and flavorings.",
nutritionsAmount: "per 100 grams",
nutritions: map[string]string{
"Calories": "231",
"TotalFat": "0 g",
"Cholesterol": "0 mg",
"Sodium": "1 mg",
"Carbohydrate": "0 g",
"Protein": "0 g",
},
},
}

c.JSON(200, gin.H{
"status": "OK",
"code": 200,
"data": d,
})

})
r.Run()
}

enter image description here

问题是,我需要对变量 d 做什么?所以数据会在浏览器中输出?

最佳答案

小写字段被认为是私有(private)的,不会被标准的 json 序列化器序列化。

更改 alcoholDrink 的字段键入,以便它们以大写字母开头:

type alcoholDrink struct {
Name string
Description string
NutritionsAmount string
Nutritions map[string]string
}

如果您想在生成的 json 中查看小写名称,可以为每个字段添加注释:
type alcoholDrink struct {
Name string `json:"name"`
Description string `json:"description"`
NutritionsAmount string `json:"nutritionsAmount"`
Nutritions map[string]string `json:"nutritions"`
}

关于go - c.JSON gin.H{()} 输出空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59509505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com