Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created March 15, 2018 04:12
Show Gist options
  • Save miguelmota/904f0fdad34eaac09c5d53098f960c5c to your computer and use it in GitHub Desktop.
Save miguelmota/904f0fdad34eaac09c5d53098f960c5c 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)
@atz
Copy link

atz commented Oct 15, 2021

You have two levels of pointers in var myStruct *MyStruct and json.Unmarshal(data, &myStruct). I made the tweak and posted it on the playground to verify:
https://play.golang.org/p/JslB6aZnp-u

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment