您好,登錄后才能下訂單哦!
這篇文章主要講解了“Golang如何實現Json轉結構體”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Golang如何實現Json轉結構體”吧!
1.請求Zabbix API,通過itemid獲取到AppName(應用集名稱)
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) func PostRequest(payload string, url string) { method := "POST" pl := strings.NewReader(payload) client := &http.Client{} req, err := http.NewRequest(method, url, pl) if err != nil { fmt.Println(err) return } req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { log.Println(err) return } fmt.Println(string(body)) } func main() { const api = "http://192.168.11.11:28080/api_jsonrpc.php" const token = "a638200c24a8bea7f78cd5cabf3d1dd5" const itemid = "33918" a := fmt.Sprintf(`{ "jsonrpc": "2.0", "method": "application.get", "params": {"itemids": "%s"}, "auth": "%s","id": 2 }`, itemid, token) PostRequest(a, api) }
響應結果:
{"jsonrpc":"2.0","result":[{"applicationid":"1574","hostid":"10354","name":"TEST","flags":"0","templateids":[]}],"id":2}
2.將響應結果(json)轉結構體,方便取值
在原來代碼的基礎上,繼續編碼。
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) type resultInfo struct { Applicationid string `json:"applicationid"` Hostid string `json:"hostid"` Name string `json:"name"` Flags string `json:"flags"` Templateids []string `json:"templateids"` } type resultArr []resultInfo type Response struct { Jsonrpc string `json:"jsonrpc"` Result resultArr `json:result` Id int `json:"id"` } type Byte []byte func JsonConvertStruct(body Byte) { var response Response json.Unmarshal([]byte(body), &response) fmt.Println(response.Result[0].Name) } func PostRequest(payload string, url string) { method := "POST" pl := strings.NewReader(payload) client := &http.Client{} req, err := http.NewRequest(method, url, pl) if err != nil { fmt.Println(err) return } req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { log.Println(err) return } JsonConvertStruct(body) } func main() { const api = "http://192.168.11.11:28080/api_jsonrpc.php" const token = "a638200c24a8bea7f78cd5cabf3d1dd5" const itemid = "33918" a := fmt.Sprintf(`{ "jsonrpc": "2.0", "method": "application.get", "params": {"itemids": "%s"}, "auth": "%s","id": 2 }`, itemid, token) PostRequest(a, api) }
結果:
TEST
感謝各位的閱讀,以上就是“Golang如何實現Json轉結構體”的內容了,經過本文的學習后,相信大家對Golang如何實現Json轉結構體這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。