Created
December 13, 2014 13:11
-
-
Save hiroosak/af65464863cda7dc494a to your computer and use it in GitHub Desktop.
json unmarshal test
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" | |
scan "github.com/mattn/go-scan" | |
) | |
type User struct { | |
Name string | |
Age uint16 | |
} | |
func (u *User) UnmarshalJSON(data []byte) error { | |
var i interface{} | |
if err := json.Unmarshal(data, &i); err != nil { | |
return err | |
} | |
if err := scan.ScanTree(i, "/Name", &u.Name); err != nil { | |
return err | |
} | |
if err := scan.ScanTree(i, "/Age", &u.Age); err != nil { | |
return err | |
} | |
return nil | |
} | |
func main() { | |
var jsonStr = `{"Name": "Ken", "Age": 32}` | |
var u User | |
err := json.Unmarshal([]byte(jsonStr), &u) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("Name: %s Age: %d\n", u.Name, u.Age) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment