I'm fairly new to Golang. And I was looking for a way to do some custom stuff for marshaling and unmarshalling json
. I have found the solution to implement Marshaller
and Unmarshaller
interfaces.
Here is my struct
with implemented interfaces (I have also implemented Stringer):
type Data struct {
Foo string `json:"foo"`
bar string
}
func (d Data) MarshalJSON() ([]byte, error) {
return []byte("{\"foo\":\"test\",\"bar\":\"data\"}"), nil
}
func (d Data) String() string {
return fmt.Sprintf("Foo: %s, bar: %s", d.Foo, d.bar)
}
func (d Data) UnmarshalJSON(b []byte) error {
d.bar = "testtest"
d.Foo = "data"
return nil
}
For Marshaller
everything works as expected:
data := &Data{}
marshal, _ := json.Marshal(data)
fmt.Println(string(marshal))
The output as expected:
{"foo":"test","bar":"data"}
But Unmarshaller doesn't work as I was expecting:
jsonData := "{\"foo\":\"test\"}"
data := Data{}
json.Unmarshal([]byte(jsonData), data)
fmt.Println(data)
This code prints:
Foo: , bar:
Is there something that I'm missing here?