Skip to content

Instantly share code, notes, and snippets.

@geraldstanje
Created July 26, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geraldstanje/be44836c2e0f1800c193 to your computer and use it in GitHub Desktop.
Save geraldstanje/be44836c2e0f1800c193 to your computer and use it in GitHub Desktop.
golang json decode example
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"time"
)
/*
I have an struct, say Obj, with a time.Time field, when I decode a stream with json.Decode into Obj the time are formatted as
2015-07-26 11:37:28.377841064 +0000 UTC while if I decode into interface{} they are formatted as 2015-07-26T11:37:28.429525113Z
how do I get 2015-07-26T11:37:28.429525113Z even when decoding into Obj?
*/
type Date struct{ time.Time }
func (d *Date) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("birthdate should be a string, got %s", data)
}
t, err := time.Parse("2006/01/02", s)
if err != nil {
return fmt.Errorf("invalid date: %v", err)
}
d.Time = t
return nil
}
type Person struct {
Name string
Born Date `json:"birthdate"`
}
func main() {
data := []byte(`
{
"name": "Gopher",
"birthdate": "2009/11/10"
}
`)
var p Person
dec := json.NewDecoder(bytes.NewReader(data))
if err := dec.Decode(&p); err != nil {
log.Fatalf("parse person: %v", err)
}
fmt.Println(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment