Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save myarik/486a5b7ec33f4cf61a056c12b4a5e4f0 to your computer and use it in GitHub Desktop.
Save myarik/486a5b7ec33f4cf61a056c12b4a5e4f0 to your computer and use it in GitHub Desktop.
Golang custom struct unmarshal function example
package main
import (
"encoding/json"
"fmt"
"log"
"time"
)
type MyStruct struct {
Name string `json:"name"`
SomeCustomType time.Time `json:"someCustomType"`
}
func (s *MyStruct) UnmarshalJSON(data []byte) error {
type Alias MyStruct
aux := &struct {
SomeCustomType int64 `json:"someCustomType"`
*Alias
}{
Alias: (*Alias)(s),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
s.SomeCustomType = time.Unix(aux.SomeCustomType, 0)
return nil
}
func main() {
data := []byte(`{"name":"bob", "someCustomType": 152108680}`)
var myStruct *MyStruct
err := json.Unmarshal(data, &myStruct)
if err != nil {
fmt.Println(err)
}
log.Println(myStruct)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment