-
-
Save alidevhere/06acf6060976b57ffcc9d4b15219de73 to your computer and use it in GitHub Desktop.
Golang custom struct unmarshal function example
This file contains hidden or 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