Lezioni del modulo (4/5)
Tag dei campi e JSON
I tag sui campi struct sono stringhe meta-dati, lette via reflection
da librerie come encoding/json, encoding/xml, validator, ORM. Si
scrivono fra backtick (raw string) subito dopo il tipo del campo.
Sintassi
type User struct {
Name string `json:"nome"`
Age int `json:"eta,omitempty"`
}Convenzione del formato: chiave:"valore" separate da spazi (NON
virgole) per più chiavi:
type User struct {
Email string `json:"email" validate:"required,email"`
}Tag json: opzioni
L'opzione più comune è json, usata da encoding/json:
| Tag | Effetto |
|---|---|
json:"nome" | Rinomina il campo in nome nell'output JSON |
json:"nome,omitempty" | Omette il campo se è allo zero value |
json:"-" | Non serializzare/deserializzare questo campo |
json:",omitempty" | Mantiene il nome del campo Go ma con omitempty |
type User struct {
Name string `json:"nome"`
Age int `json:"eta,omitempty"`
Password string `json:"-"`
}
u := User{Name: "Ada", Age: 0, Password: "segreto"}
b, _ := json.Marshal(u)
fmt.Println(string(b)) // {"nome":"Ada"}Age viene omesso (zero value 0 + omitempty); Password è
escluso del tutto.
Marshal e Unmarshal
// struct -> JSON
b, err := json.Marshal(u)
// JSON -> struct (serve un PUNTATORE)
var u2 User
err = json.Unmarshal(b, &u2)Unmarshal accetta solo un puntatore, perché deve scrivere nei campi
del valore.
Altri tag comuni
xml:"..."—encoding/xmlyaml:"..."— yaml.v3db:"..."— sqlx / pgxvalidate:"..."— go-playground/validatorform:"..."— gin / echo binding
Le librerie li leggono via reflection (reflect.StructTag.Get("json")):
sono solo stringhe finché qualcuno non le interpreta.
Prova tu
Aggiungi al campo Name il tag json:"nome" e al campo Age il tag json:"eta".
Mostra suggerimento
I tag sono raw string fra backtick subito dopo il tipo del campo.
Soluzione disponibile dopo 3 tentativi
Aggiungi al campo Age l'opzione omitempty: deve essere omesso quando vale 0.
Mostra suggerimento
Le opzioni vengono dopo il nome, separate da virgola: json:"nome,omitempty".
Soluzione disponibile dopo 3 tentativi
Cosa stampa con i tag json:"nome" e json:"eta"?
u := User{Name: "Ada", Age: 36}
b, _ := json.Marshal(u)
fmt.Println(string(b))Recap
- I tag sono raw string fra backtick:
`chiave:"valore" chiave2:"valore2"`. json:"nome": rinomina.omitempty: omette se zero value.-: esclude.- Campi NON esportati (minuscoli) sono ignorati da
encoding/json. json.Marshal(v)↔json.Unmarshal(data, &v)(puntatore).- Stesso meccanismo per
xml,yaml,db,validate,form, …