Francesc Campoy | c9f0190 | 2017-02-17 11:23:53 -0800 | [diff] [blame^] | 1 | // +build OMIT |
| 2 | |
Francesc Campoy | 926adaf | 2017-01-31 14:33:26 +0100 | [diff] [blame] | 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "log" |
| 9 | ) |
| 10 | |
| 11 | func main() { |
| 12 | in := []byte(` |
| 13 | { |
| 14 | "full_name": "Gopher", |
| 15 | "age": 7, |
| 16 | "social_security": 1234 |
| 17 | }`) |
| 18 | |
| 19 | var p Person |
| 20 | if err := json.Unmarshal(in, &p); err != nil { |
| 21 | log.Fatal(err) |
| 22 | } |
| 23 | fmt.Printf("%+v\n", p) |
| 24 | } |
| 25 | |
| 26 | type Person struct { |
| 27 | Name string |
| 28 | AgeYears int |
| 29 | SSN int |
| 30 | } |
| 31 | |
| 32 | func (p *Person) UnmarshalJSON(data []byte) error { |
| 33 | var aux struct { |
| 34 | Name string `json:"full_name"` |
| 35 | AgeYears int `json:"age"` |
| 36 | SSN int `json:"social_security"` |
| 37 | } |
| 38 | if err := json.Unmarshal(data, &aux); err != nil { |
| 39 | return err |
| 40 | } |
| 41 | *p = Person{ |
| 42 | Name: aux.Name, |
| 43 | AgeYears: aux.AgeYears, |
| 44 | SSN: aux.SSN, |
| 45 | } |
| 46 | *p = Person(aux) |
| 47 | return nil |
| 48 | } |