2015-05-25 6 views
11

Voglio analizzare un oggetto JSON in Go, ma voglio specificare valori predefiniti per i campi che non vengono forniti. Ad esempio, ho il tipo struct:Come specificare i valori predefiniti durante l'analisi di JSON in Go

type Test struct { 
    A string 
    B string 
    C string 
} 

I valori predefiniti per A, B, e C, sono "a", "b" e "c" rispettivamente. Questo vuol dire che quando ho analizzare il JSON:

{"A": "1", "C": 3} 

voglio ottenere lo struct:

Test{A: "1", B: "b", C: "3"} 

Questo è possibile utilizzando il pacchetto integrato encoding/json? Altrimenti, esiste una libreria Go con questa funzionalità?

risposta

37

Ciò è possibile utilizzando codifica/json: quando si chiama json.Unmarshal, non è necessario assegnargli una struttura vuota, è possibile assegnarne una con valori predefiniti.

Per esempio:

var example []byte = []byte(`{"A": "1", "C": "3"}`) 

out := Test{ 
    A: "default a", 
    B: "default b", 
    // default for C will be "", the empty value for a string 
} 
err := json.Unmarshal(example, &out) // <-- 
if err != nil { 
    panic(err) 
} 
fmt.Printf("%+v", out) 

Esecuzione this example in the Go playground rendimenti {A:1 B:default b C:3}.

Come si può vedere, json.Unmarshal(example, &out) unmarshals JSON in out, sovrascrivendo i valori specificati nel JSON, ma lasciando gli altri campi invariati.

3

Nel caso in cui u hanno una lista o una mappa del Test struct la risposta accettata non è più possibile, ma può essere facilmente esteso con un metodo UnmarshalJSON:

func (t *Test) UnmarshalJSON(data []byte) error { 
    type testAlias Test 
    test := &testAlias{ 
    B: "default B", 
    } 

    _ = json.Unmarshal(data, test) 

    *t = Test(*test) 
    return nil 
} 

I testAlias ​​è necessario per evitare che le chiamate ricorsive a UnmarshalJSON . Funziona perché un nuovo tipo non ha metodi definiti.

https://play.golang.org/p/qiGyjRbNHg

Problemi correlati