Created
July 31, 2017 09:51
-
-
Save wudi/0e492a33889285280018e2e829f06fe9 to your computer and use it in GitHub Desktop.
demo.go
This file contains hidden or 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" | |
| ) | |
| type Source struct { | |
| ID string `json:"id"` | |
| Title string `json:"title"` | |
| Types string `json:"type"` | |
| Partition interface{} `json:"partition"` | |
| } | |
| func main() { | |
| jsonStr1 := `{ | |
| "id": "node1", | |
| "name": "name1", | |
| "partition": [ | |
| "title", | |
| "type", | |
| "value" | |
| ] | |
| }` | |
| var s1 Source | |
| if err := json.Unmarshal([]byte(jsonStr1), &s1); err != nil { | |
| panic(err) | |
| } | |
| // 类型推断 | |
| if p, ok := s1.Partition.([]interface{}); ok { | |
| for i, v := range p { | |
| fmt.Printf("Index: %d Value: %s\n", i, v) | |
| } | |
| } | |
| jsonStr2 := `{ | |
| "id": "node1", | |
| "name": "name1", | |
| "partition": { | |
| "key1": "value1", | |
| "key2": "value2" | |
| } | |
| }` | |
| var s2 Source | |
| if err := json.Unmarshal([]byte(jsonStr2), &s2); err != nil { | |
| panic(err) | |
| } | |
| // 类型推断 | |
| if p, ok := s2.Partition.(map[string]interface{}); ok { | |
| for k, v := range p { | |
| fmt.Printf("Key: %s Value: %s\n", k, v) | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: