gin框架返回JSON
package mainimport ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.GET("/json", func(c *gin.Context) {//用map序列化//方法一:用map,后面用接口类型// data := map[string]interface{}{// "name": "蒋志宇",// "age": 18,// "身高": "一米八",// }//方法二:直接用gin.Hdata := gin.H{"name": "蒋志宇","age": 18,"身高": "一米八",}c.JSON(http.StatusOK, data)})//方法三:结构体type msg struct {Name stringAge intMessage string}r.GET("/another_json", func(c *gin.Context) {data := msg{"小马哥",35,"心如火,爱情似烈火",}c.JSON(http.StatusOK, data) //JSON的序列化})r.Run(":9000")}
结构体内元素若想被访问,首字母得大写,但返回回去的如果不想大写,就要用tag
//方法三:结构体type msg struct {Name string `json:"name"`Age int `json:"age"`Message string `json:"message"`}
效果: