2014-12-28 13 views
8

Come eseguire il marshalling di una struttura nidificata in JSON? So come eseguire il marshalling della struct senza alcuna struttura annidata. Tuttavia quando provo a rendere la risposta JSON simile a questa:Strutture nidificate di marshall in JSON

{"genre": {"country": "taylor swift", "rock": "aimee"}} 

Mi imbatto in problemi.

Il mio codice è simile al seguente:

Go:

type Music struct { 
    Genre struct { 
    Country string 
    Rock string 
    } 
} 

resp := Music{ 
    Genre: { // error on this line. 
    Country: "Taylor Swift", 
    Rock: "Aimee", 
    }, 
} 

js, _ := json.Marshal(resp) 
w.Write(js) 

Tuttavia, ottengo l'errore

Missing type in composite literal

Come risolvo questo?

risposta

13

Ecco il composito letterale per il vostro tipo:

resp := Music{ 
    Genre: struct { 
     Country string 
     Rock string 
    }{ 
     Country: "Taylor Swift", 
     Rock: "Aimee", 
    }, 
} 

playground example

È necessario ripetere il tipo anonimo nel letterale. Per evitare la ripetizione, ti consiglio di definire un tipo per Genere. Inoltre, utilizzare i tag di campo per specificare i nomi dei tasti in minuscolo nell'output.

type Genre struct { 
    Country string `json:"country"` 
    Rock string `json:"rock"` 
} 

type Music struct { 
    Genre Genre `json:"genre"` 
} 

resp := Music{ 
    Genre{ 
     Country: "Taylor Swift", 
     Rock: "Aimee", 
    }, 
} 

playground example

+0

grazie! il primo esempio non ha funzionato anche se – user3918985

Problemi correlati