通过RenderJson传递多个值

huangapple go评论87阅读模式
英文:

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: &quot;&quot;, Results: {&lt;a_struct&gt;, &lt;string&gt;})

I know that you can pass one variable/value/struct like:

return c.RenderJson(Response{Err: &quot;&quot;, Results: &lt;a_struct&gt;)

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: &quot;&quot;,
               Results: map[string]interface{}{
                   &quot;a_struct&quot;: a_struct,
                   &quot;other_thing&quot;: 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:&quot;foo&quot; xml:&quot;foo&quot; `
    Bar int ` json:&quot;bar&quot; xml:&quot;bar&quot; `
}

func (c MyController) MyAction() revel.Result {
    data := make(map[string]interface{})
    data[&quot;error&quot;] = nil
    stuff := Stuff{Foo: &quot;xyz&quot;, Bar: 999}
    data[&quot;stuff&quot;] = stuff
    return c.RenderJson(data)
    //return c.RenderXml(data)
}

huangapple
  • 本文由 发表于 2016年10月28日 14:17:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/40299133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定