英文:
Passing multiple values through RenderJson
问题
学习'go'。通过RenderJson方法是否可以传递多个值?类似于:
return c.RenderJson(Response{Err: "", Results: {<a_struct>, <string>}})
我知道可以传递一个变量/值/结构体,例如:
return c.RenderJson(Response{Err: "", Results: <a_struct>})
为了实现我的目的,我可以创建一个包含'a_struct'和'string'的结构体,然后将其传递。想知道是否可以通过传递多个值来实现。
英文:
Learning 'go'. Is it possible to pass multiple values through RenderJson method. Something like :
return c.RenderJson(Response{Err: "", Results: {<a_struct>, <string>})
I know that you can pass one variable/value/struct like:
return c.RenderJson(Response{Err: "", Results: <a_struct>)
To achieve my purpose, I can create an struct of 'a_struct' and 'string' and the pass it along. Wondering if it can be achieved by passing muliple values.
答案1
得分: 1
根据https://godoc.org/github.com/revel/revel#Controller.RenderJson的说明,RenderJson只接受一个interface{}
类型的参数。所以我会期望以下代码:
return c.RenderJson(
Response{
Err: "",
Results: map[string]interface{}{
"a_struct": a_struct,
"other_thing": someString,
},
}
)
英文:
According to https://godoc.org/github.com/revel/revel#Controller.RenderJson, RenderJson just takes an interface{}
. So I would expect
return c.RenderJson(
Response{
Err: "",
Results: map[string]interface{}{
"a_struct": a_struct,
"other_thing": someString,
},
}
)
答案2
得分: 1
是的,这是可能的。
来自Revel手册的示例:
// 简单示例
type Stuff struct {
Foo string `json:"foo" xml:"foo"`
Bar int `json:"bar" xml:"bar"`
}
func (c MyController) MyAction() revel.Result {
data := make(map[string]interface{})
data["error"] = nil
stuff := Stuff{Foo: "xyz", Bar: 999}
data["stuff"] = stuff
return c.RenderJson(data)
//return c.RenderXml(data)
}
英文:
Yes it is possible
Example from Revel's manual:
// Simple example
type Stuff struct {
Foo string ` json:"foo" xml:"foo" `
Bar int ` json:"bar" xml:"bar" `
}
func (c MyController) MyAction() revel.Result {
data := make(map[string]interface{})
data["error"] = nil
stuff := Stuff{Foo: "xyz", Bar: 999}
data["stuff"] = stuff
return c.RenderJson(data)
//return c.RenderXml(data)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论