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

使用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)

}

  • 写回答

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": [...]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?