golang 框架 beego ServeJSON的数据到底应该用什么类型?

mystruct := &JSONStruct{0, "hello"}
fmt.Println(mystruct)
c.Data["json"] = mystruct
c.ServeJSON()

按以上写法是通过的
但是

mystruct := JSONStruct{0, "hello"}

这样写也可以通过
到底哪种合理?

阅读 6k
1 个回答

我没有太理解你的问题, 你是想问 c.Data["json"] 是 JSONStruct的值和指针的区别吗, 为什么用指针和值都可以得到正确的输出?这个问题我建议你看 c.ServeJSON()的源码就明白了

// ServeJson sends a json response with encoding charset.
func (c *Controller) ServeJson(encoding ...bool) {
    var hasIndent bool
    var hasencoding bool
    if RunMode == "prod" {
        hasIndent = false
    } else {
        hasIndent = true
    }
    if len(encoding) > 0 && encoding[0] == true {
        hasencoding = true
    }
    c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
}

// Json writes json to response body.
// if coding is true, it converts utf-8 to \u0000 type.
func (output *BeegoOutput) Json(data interface{}, hasIndent bool, coding bool) error {
    output.Header("Content-Type", "application/json; charset=utf-8")
    var content []byte
    var err error
    if hasIndent {
        content, err = json.MarshalIndent(data, "", "  ")
    } else {
        content, err = json.Marshal(data)
    }
    if err != nil {
        http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
        return err
    }
    if coding {
        content = []byte(stringsToJson(string(content)))
    }
    output.Body(content)
    return nil
}

实际这个方法是对json序列化和 http 响应的封装, 只是直接把 c.Data["json"] 传递给json组件了而已, json 内部会进行反射, 会自动处理指针类型的数据,和我们平时使用没有任何区别, 只要是 json组件可以序列化的数据都可以给 c.Data["json"] ,而 c.Data 是 map[interface{}]interface{} 类型的数据

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题