Come ispirato dalla risposta di zeebo e hash nei commenti a questa risposta:
http://play.golang.org/p/pUCBUgrjZC
package main
import "fmt"
import "time"
import "encoding/json"
type jsonTime struct {
time.Time
f string
}
func (j jsonTime) format() string {
return j.Time.Format(j.f)
}
func (j jsonTime) MarshalText() ([]byte, error) {
return []byte(j.format()), nil
}
func (j jsonTime) MarshalJSON() ([]byte, error) {
return []byte(`"` + j.format() + `"`), nil
}
func main() {
jt := jsonTime{time.Now(), time.Kitchen}
if jt.Before(time.Now().AddDate(0, 0, 1)) { // 1
x := map[string]interface{}{
"foo": jt,
"bar": "baz",
}
data, err := json.Marshal(x)
if err != nil {
panic(err)
}
fmt.Printf("%s", data)
}
}
Questa soluzione embeds la time.time nella struct jsonTime. L'incorporamento promuove tutto il tempo. Metodi di tempo per la struttura jsonTime, consentendo il loro uso senza conversione di tipo esplicita (vedi // 1).
Incorporare un orario. Il tempo ha lo svantaggio di promuovere anche il metodo MarshalJSON, che il codice di codifica/json marshalling dà priorità al metodo MarshalText per ragioni di compatibilità all'indietro (MarshalText was added in Go 1.2, MarshalJSON è anteriore a tale). Di conseguenza l'ora predefinita. Il formato del tempo viene utilizzato al posto di un formato personalizzato fornito da MarshalText.
Per risolvere questo problema, ignoriamo MarshalJSON per la struttura jsonTime.
come faresti a rispettare questo "omitempty" nel campo del tempo? – nojo