这篇文章主要讲解了“golang怎么实现JSON转结构体”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Golang怎么实现json转结构体”吧!请求Zabbix api,通过itemid获取
这篇文章主要讲解了“golang怎么实现JSON转结构体”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Golang怎么实现json转结构体”吧!
请求Zabbix api,通过itemid获取到AppName(应用集名称)
package mainimport ( "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}
将响应结果(json)转结构体,方便取值
在原来代码的基础上,继续编码。
package mainimport ( "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 []resultInfotype Response struct { Jsonrpc string `json:"jsonrpc"` Result resultArr `json:result` Id int `json:"id"`}type Byte []bytefunc 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转结构体这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!
--结束END--
本文标题: Golang怎么实现Json转结构体
本文链接: https://lsjlt.com/news/349362.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-05
2024-04-05
2024-04-05
2024-04-04
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-04
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0