构造JSON响应的简单方法?

时间:2019-10-21 01:51:32

标签: c# json

在golang中,有一个SELECT cast((t1.Opened/t1.OverAll) as decimal(18,4)) * 100.00 as 'AverageOpen' FROM (SELECT SubscriberKey , SUM(CASE WHEN PreviousMonth <= 1 AND SendType = 'Auto' AND Opened = 1 THEN 1 ELSE 0 END) Opened, , SUM(CASE WHEN PreviousMonth <= 1 AND SendType = 'Auto' THEN 1 ELSE 0 END) OverAll FROM Data GROUP BY SubscriberKey) as t1 框架可以自定义json结构:

gin

如果用户还可以,请返回:

authorized.GET("/secrets", func(c *gin.Context) {
    // get user, it was set by the BasicAuth middleware
    user := c.MustGet(gin.AuthUserKey).(string)
    if secret, ok := secrets[user]; ok {
        c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
    } else {
        c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET"})
    }
})

否则返回:

{
  "user: "user",
  "secret: "secret"
}

对于自定义json响应确实很方便,但是根据我在C#中的经验,我必须创建另一个Class来构造json响应。

是否有与C#中的golang相同的方法来轻松构造json响应?

1 个答案:

答案 0 :(得分:-1)

c.JSON还支持go struct参数

type Response struct {
  User string  `json:"user"`
  Secret string `json:"secret"`
}

c.JSON(http.StatusOK, Response{User:"your name", Secret:"secret"})