Guest User

Untitled

a guest
Mar 23rd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "time"
  8. )
  9.  
  10. type MyStruct struct {
  11. Name string `json:"name"`
  12. SomeCustomType time.Time `json:"someCustomType"`
  13. }
  14.  
  15. func (s *MyStruct) UnmarshalJSON(data []byte) error {
  16. type Alias MyStruct
  17. aux := &struct {
  18. SomeCustomType int64 `json:"someCustomType"`
  19. *Alias
  20. }{
  21. Alias: (*Alias)(s),
  22. }
  23. if err := json.Unmarshal(data, &aux); err != nil {
  24. return err
  25. }
  26. s.SomeCustomType = time.Unix(aux.SomeCustomType, 0)
  27. return nil
  28. }
  29.  
  30. func main() {
  31. data := []byte(`{"name":"bob", "someCustomType": 152108680}`)
  32. var myStruct *MyStruct
  33. err := json.Unmarshal(data, &myStruct)
  34. if err != nil {
  35. fmt.Println(err)
  36. }
  37.  
  38. log.Println(myStruct)
Add Comment
Please, Sign In to add comment