Skip to content

Instantly share code, notes, and snippets.

@hiroosak
Last active August 29, 2015 14:11
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 hiroosak/2cc2ab4a8da6cc7d78c4 to your computer and use it in GitHub Desktop.
Save hiroosak/2cc2ab4a8da6cc7d78c4 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
simpleJson "github.com/bitly/go-simplejson"
)
type User struct {
Name string
Age uint16
Articles []Article
}
func (u *User) UnmarshalJSON(data []byte) error {
js, err := simpleJson.NewJson(data)
if err != nil {
return err
}
u.Name, err = js.Get("Name").String()
if err != nil {
return err
}
var age uint64
age, err = js.Get("Age").Uint64()
if err != nil {
return err
}
u.Age = uint16(age)
// Article
var bytes []byte
bytes, err = js.Get("Articles").Encode()
if err != nil {
return err
}
var as []Article
if err := json.Unmarshal(bytes, &as); err != nil {
return err
}
u.Articles = as
return nil
}
type Article struct {
Title string
Content string
}
func (a *Article) UnmarshalJSON(data []byte) error {
js, err := simpleJson.NewJson(data)
if err != nil {
return err
}
a.Title, err = js.Get("Title").String()
if err != nil {
return err
}
a.Content, err = js.Get("Content").String()
if err != nil {
return err
}
return nil
}
func main() {
var jsonStr = `{
"Name": "Ken",
"Age": 32,
"Articles": [
{"Title": "Title A", "Content": "content"},
{"Title": "Title B", "Content": "content"}
]
}`
var u User
err := json.Unmarshal([]byte(jsonStr), &u)
if err != nil {
panic(err)
}
fmt.Println(u) // {Ken 32 [{Title A content} {Title B content}]}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment