dongza3124
2014-11-18 22:00
浏览 892
已采纳

使用GO将结构数组返回为Json Response

I am building a REST api in GO and I am able to fetch the JSON response from the server. I am looking forward to store the JSON response in sort of a container (array) and return that structure from the function. I have my data structures defined something like this - {

type Payload struct {
    Stuff []Data `json:"data"`  // holds the JSON response returned
}

type Container struct {
    container []Payload
}

type ListContainersResponse struct {
    Data []Container    // want this thing to be returned from the function
}


func (client *Client) ListContainers() (ListContainersResponse, error) {
   // fetches the JSON response 
   var p Payload 

    // XYZ is something of the type ListContainersResponse which needs to be returned 
   return  XYZ
}

}

iterating over p gives me my JSON structure and I want to append it to a Data[] container which can hold this returned JSON response and returned back from the function. I tried playing around with it but get some exceptions. Could someone help me with this?

Thanks, I got my code working by doing something like this {

var result ListContainersResponse
    var temp Container
    temp.container = append(temp.container, p)
    result.Data = append(result.Data, temp)

}

图片转代码服务由CSDN问答提供 功能建议

我正在GO中构建一个REST api,并且能够从服务器获取JSON响应。 我期待将JSON响应存储在某种容器(数组)中,并从函数中返回该结构。 我已经定义了这样的数据结构- {

  type Payload struct {
 Stuff [] Data`json:“ data”`//保存JSON响应 返回
} 
 
type容器结构{
容器[]有效负载
} 
 
类型ListContainersResponse结构{
数据[]容器//希望从函数中返回此内容
} 
 \  n 
func(客户*客户)ListContainers()(ListContainersResponse,错误){
 //获取JSON响应
 var p有效负载
 
 // XYZ是ListContainersResponse类型,需要返回
 返回XYZ 
} 
   
 
 

}

迭代p给我我的JSON结构,我想将其附加到 Data []容器,可以容纳此返回的JSON响应并从该函数返回。 我试着玩它,但有一些例外。 有人可以帮我吗?

谢谢,我通过执行类似 {

  var结果ListContainersResponse的操作使代码工作 
 var temp容器
 temp.container = append(temp.container,p)
结果.Data = append(result.Data,temp)
   
 
 

}

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongxian1921 2014-11-19 01:26
    最佳回答

    Assuming you've already got the JSON decoded into an instance of Payload p.

    func (client *Client) ListContainers() (ListContainersResponse, error) {
       // fetches the JSON response 
       var p Payload 
    
       XYZ := ListContainersResponse {
           Data: []Container {
               container: []Payload {
                   {p},
               },
           },
       }
    
       // XYZ is something of the type ListContainersResponse which needs to be returned 
       return XYZ
    }
    

    Additionally, in case any else is interested, here is how I would get the JSON into the struct:

    var p Payload
    decoder := json.NewDecoder(r.Body)
    err := decoder.Decode(&p)
    

    Where r is of type http.Request. I expect the json string looks something like:

    {
        "data": [...]
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题