Beego Controller 中的 JSON 响应

标签 json struct go beego

我是 beego 的新手,试图在路由上获取 JSON 响应。

我有一个这样定义的 Controller 。

package controllers

import (
    "github.com/astaxie/beego"
)

type ErrorController struct {
    beego.Controller
}

type ErrorJson struct {
    s string
    d string
}

func (this *ErrorController) Get() {

    var responseJson ErrorJson
    responseJson = ErrorJson{
        s: "asdf",
        d: "qwer",
    }

    this.Data["json"] = responseJson
    this.ServeJson()
}

我的路由器定义为

beego.Router("/api", &controllers.ErrorController{})

当我访问路由时,我得到一个没有任何属性的空 JSON 对象。

{}

如果我用字符串替换 json 结构,我会得到响应。所以beego是知道 Controller 和方法的。

this.Data["json"] = "Hello World"

我做错了什么?

最佳答案

您需要export ErrorJson 中的字段,名称以大写字符开头。使用字段标签指定输出中的小写名称。

type ErrorJson struct {
    S string `json:"s"`
    D string `json:"d"`
}

encoding/json 包和类似的包会忽略未导出的字段。

关于Beego Controller 中的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34127023/

相关文章:

iphone - 处理项目中的 JSON 响应

json - 仅在 JSON 之后加载 tableView

macos - 使用反射运行 Go 服务器时 Mac 反复要求接受网络连接

amazon-web-services - 从指定的 S3 目录列表中检索内容

MongoDB 在 golang 中使用 $or 和 $and 的组合查找查询

java - JSON 解码去除小数尾随零

c# - 在处理程序中将 Json 反序列化为 Object

c++ - VS2008 传递变量 - 结构与结构组件 - 优点/缺点?

c - 嵌套结构中的数据如何存储和填充?

json - 使用 2 种嵌套类型解析 JSON