Sto costruendo una API REST in GO e sono in grado di farlorecuperare la risposta JSON dal server. Non vedo l'ora di memorizzare la risposta JSON in una sorta di contenitore (array) e restituire tale struttura dalla funzione. Ho definito le mie strutture dati qualcosa del genere - {
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
}
}
iterando su p mi dà la mia struttura JSON e iodesidera aggiungerlo a un contenitore Data [] che possa contenere questa risposta JSON restituita e restituito dalla funzione. Ho provato a giocarci, ma ho delle eccezioni. Qualcuno potrebbe aiutarmi con questo?
Grazie, ho ottenuto il mio codice lavorando facendo qualcosa di simile {
var result ListContainersResponse
var temp Container
temp.container = append(temp.container, p)
result.Data = append(result.Data, temp)
}
risposte:
0 per risposta № 1Supponendo che tu abbia già decodificato il JSON in un'istanza di 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
}
Inoltre, nel caso in cui qualcun altro sia interessato, ecco come vorrei ottenere il JSON nella struttura:
var p Payload
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&p)
Dove r
è di tipo http.Request
. Mi aspetto che la stringa JSON assomigli a qualcosa:
{
"data": [...]
}