Provando a json Marshal una struttura che contiene 2 campi di tempo. Ma voglio solo che il campo arrivi se ha un valore temporale. Quindi sto usando json:",omitempty"
ma non funziona.Golang JSON omitempty Con time.Time Field
In che modo è possibile impostare il valore Date in modo che json.Marshal lo tratti come un valore vuoto (zero) e non lo includa nella stringa json?
Playground: http://play.golang.org/p/QJwh7yBJlo
Actual Risultato:
{ "Timestamp": "2015-09-18T00: 00: 00Z", "Data": "0001-01-01T00: 00: 00Z "}
Risultato desiderato:
{ "Timestamp": "2015-09-18T00: 00: 00Z"}
Codice:
package main
import (
"encoding/json"
"fmt"
"time"
)
type MyStruct struct {
Timestamp time.Time `json:",omitempty"`
Date time.Time `json:",omitempty"`
Field string `json:",omitempty"`
}
func main() {
ms := MyStruct{
Timestamp: time.Date(2015, 9, 18, 0, 0, 0, 0, time.UTC),
Field: "",
}
bb, err := json.Marshal(ms)
if err != nil {
panic(err)
}
fmt.Println(string(bb))
}
La funzione [non funziona con time.Time] (https://github.com/golang/go/blob/1fd78e1f600d10475b85381427bda9f14f86e0f0/src/encoding/json/encode.go#L278-L294). –
Probabilmente il modo più semplice per raggiungere il tuo obiettivo sarebbe quello di consentire a MyStruct di implementare http://golang.org/pkg/encoding/json/#Unmarshaler. – Volker
Buono a sapersi e buon consiglio. Grazie! –