Last active
August 29, 2015 14:11
-
-
Save hiroosak/2cc2ab4a8da6cc7d78c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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