2013-03-16 12 views
14

Sto utilizzando Go 1.0.3 su Mac OS X 10.8.2 e sto sperimentando con il pacchetto json, cercando di eseguire il marshalling di una struttura su json, ma continuo a ricevere un vuoto {} json oggetto.Le mie strutture non eseguono il marshalling in JSON

Il valore err è nullo, quindi nulla è sbagliato in base alla funzione json.Marshal e la struttura è corretta. Perché sta succedendo?

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type Address struct { 
    street string 
    extended string 
    city string 
    state string 
    zip string 
} 

type Name struct { 
    first string 
    middle string 
    last string 
} 

type Person struct { 
    name Name 
    age int 
    address Address 
    phone string 
} 

func main() { 
    myname := Name{"Alfred", "H", "Eigenface"} 
    myaddr := Address{"42 Place Rd", "Unit 2i", "Placeton", "ST", "00921"} 
    me := Person{myname, 24, myaddr, "000 555-0001"} 

    b, err := json.Marshal(me) 

    if err != nil { 
    fmt.Println(err) 
    } 

    fmt.Println(string(b)) // err is nil, but b is empty, why? 
    fmt.Println("\n") 
    fmt.Println(me)   // me is as expected, full of data 
} 

risposta

33

È necessario rendere pubblici i campi che si desidera effettuare il marshalling. Ti piace questa:

type Address struct { 
    Street string 
    Extended string 
    City string 
    State string 
    Zip string 
} 

err è nil perché tutti i campi esportati, in questo caso non ce ne sono, sono stati marshalling correttamente.

esempio di lavoro: http://play.golang.org/p/0Q8TIvZwuj

Scopri i documenti http://godoc.org/encoding/json/#Marshal

+1

Quello è stato, ho sorvolato la linea "Ogni campo struct_exported_". Grazie. – tlehman

+0

grazie per aver segnalato il "pubblico". –

4

Si noti che è anche possibile manipolare ciò che il nome dei campi nel JSON generato sono effettuando le seguenti operazioni:

type Name struct { 
    First string `json:"firstname"` 
    Middle string `json:"middlename"` 
    Last string `json:"lastname"` 
} 
+0

Mi piace questo modo di associare le strutture e gli oggetti json. – tlehman

Problemi correlati