Skip to content

Instantly share code, notes, and snippets.

@yasarix
Created March 27, 2016 04:16
Show Gist options
  • Save yasarix/a7f19ef1460d119c5727 to your computer and use it in GitHub Desktop.
Save yasarix/a7f19ef1460d119c5727 to your computer and use it in GitHub Desktop.
time.Duration to JSON
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type Duration struct {
time.Duration
}
func (d *Duration) UnmarshalJSON(b []byte) (err error) {
if b[0] == '"' {
sd := string(b[1 : len(b)-1])
d.Duration, err = time.ParseDuration(sd)
return
}
var id int64
id, err = json.Number(string(b)).Int64()
d.Duration = time.Duration(id)
return
}
func (d Duration) MarshalJSON() (b []byte, err error) {
return []byte(fmt.Sprintf(`"%s"`, d.String())), nil
}
type Ex struct {
S Duration
I Duration
}
func main() {
var ex Ex
in := strings.NewReader(`{"S": "15s350ms", "I": 400000}`)
err := json.NewDecoder(in).Decode(&ex)
if err != nil {
panic(err)
}
fmt.Println("Decoded:", ex)
out, err := json.Marshal(ex)
if err != nil {
panic(err)
}
fmt.Println("Encoded:", string(out))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment