Skip to content

Instantly share code, notes, and snippets.

@ugorji
Created March 11, 2015 21:06
Show Gist options
  • Save ugorji/8bb851bf49cff1c3d4d9 to your computer and use it in GitHub Desktop.
Save ugorji/8bb851bf49cff1c3d4d9 to your computer and use it in GitHub Desktop.
package main
import (
"strconv"
"time"
"github.com/ugorji/go/codec"
"encoding/json"
)
func main() {
val, err := Codecdemo()
if err != nil {
panic(err)
}
m := new(Wrapper)
if err = json.Unmarshal(val, m); err != nil {
println("val:", string(val))
panic(err)
}
println("val:", string(val))
}
type MapVal struct {
Name string
Time time.Time
}
type Entry struct {
Vals map[string]*MapVal
}
type Wrapper struct {
Entries []*Entry
}
func Codecdemo() ([]byte, error) {
w := new(Wrapper)
w.Entries = make([]*Entry, 1)
e := new(Entry)
w.Entries[0] = e
w.Entries[0].Vals = make(map[string]*MapVal, 0)
for i := 0; i < 4; i++ {
m := new(MapVal)
m.Name = strconv.Itoa(i + 1)
m.Time = time.Now()
w.Entries[0].Vals[m.Name] = m
}
b := make([]byte, 0)
h := new(codec.JsonHandle)
enc := codec.NewEncoderBytes(&b, h)
if err := enc.Encode(w); err != nil {
return nil, err
}
return b, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment