1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 ) 7 8 /* 9 10 GO类型和JSON类型的对应关系 11 • bool 代表 JSON booleans, 12 • float64 代表 JSON numbers, 13 • string 代表 JSON strings, 14 • nil 代表 JSON null. 15 16 三方开源库: 17 https://github.com/bitly/go-simplejson 18 */ 19 20 type Server struct { 21 ServerName string 22 ServerIP string 23 } 24 25 type Serverslice struct { 26 Servers []Server 27 } 28 29 type Server2 struct { 30 ServerName string `json:"serverName"` 31 ServerIP string `json:"serverIP"` 32 } 33 34 type Serverslice2 struct { 35 Servers []Server2 `json:"servers"` 36 } 37 38 func main() { 39 fmt.Println("********************") 40 jsonUnmarshal() 41 fmt.Println("********************") 42 jsonUnmarshal2() 43 fmt.Println("********************") 44 jsonMarshal() 45 fmt.Println("********************") 46 jsonMarshal2() 47 } 48 49 func jsonUnmarshal() { 50 var s Serverslice 51 str := `{"servers": 52 [{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"}, 53 {"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}` 54 json.Unmarshal([]byte(str), &s) 55 fmt.Println(s) 56 } 57 58 func jsonUnmarshal2() { 59 b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`) 60 var f interface{} 61 json.Unmarshal(b, &f) 62 m := f.(map[string]interface{}) 63 for k, v := range m { 64 switch vv := v.(type) { 65 case string: 66 fmt.Println(k, "is string", vv) 67 case int: 68 fmt.Println(k, "is int", vv) 69 case float64: 70 fmt.Println(k, "is float64", vv) 71 case []interface{}: 72 fmt.Println(k, "is an array:") 73 for i, u := range vv { 74 fmt.Println(i, u) 75 } 76 default: 77 fmt.Println(k, "is of a type i don't konw how handle") 78 } 79 } 80 } 81 82 func jsonMarshal() { 83 var s Serverslice 84 s.Servers = append(s.Servers, Server{ServerName: "Shanghai_VPN", ServerIP: "127.0.0.1"}) 85 s.Servers = append(s.Servers, Server{ServerName: "Beijing_VPN", ServerIP: "127.0.0.2"}) 86 b, err := json.Marshal(s) 87 if err != nil { 88 fmt.Println("json err:", err) 89 } 90 fmt.Println(string(b)) 91 } 92 93 func jsonMarshal2() { 94 var s Serverslice2 95 s.Servers = append(s.Servers, Server2{ServerName: "Shanghai_VPN", ServerIP: "127.0.0.1"}) 96 s.Servers = append(s.Servers, Server2{ServerName: "Beijing_VPN", ServerIP: "127.0.0.2"}) 97 b, err := json.Marshal(s) 98 if err != nil { 99 fmt.Println("json err:", err) 100 } 101 fmt.Println(string(b)) 102 }
有疑问加站长微信联系(非本文作者)