Created
March 15, 2018 04:12
-
-
Save miguelmota/904f0fdad34eaac09c5d53098f960c5c to your computer and use it in GitHub Desktop.
Golang custom struct unmarshal function example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
You have two levels of pointers in
var myStruct *MyStruct
andjson.Unmarshal(data, &myStruct)
. I made the tweak and posted it on the playground to verify:https://play.golang.org/p/JslB6aZnp-u