Go:Json转结构体

该代码示例展示了如何使用Go语言发送POST请求到Zabbix API来获取应用集名称(AppName)。首先定义了请求payload和URL,然后通过HTTP客户端发送请求并解析返回的JSON响应,将结果转换为结构体便于数据提取。响应结果显示为' TEST',说明成功获取了AppName。

解决实际需求,案例分享。

  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}
  1. 将响应结果(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
  1. 来自最好的总结

人生苦短,建议你还是用python吧!

本文转载于(喜欢的盆友关注我们):https://mp.weixin.qq.com/s/mBbf0DuUh1Af3vi2DBE7DA

1)JSON字符串还原为结构体; 2)访问结构体的字段值; uses SynCommons; const // JSON字符串 JSON1 = '{' + #13#10 + '"glossary": {' + #13#10 + '"title": "中国",' + #13#10 + ' "GlossDiv": {' + #13#10 + '"title": "湖南省",' + #13#10 + ' "GlossList": {' + #13#10 + '"GlossEntry": {' + #13#10 + '"ID": "湘乡市",' + #13#10 + ' "SortAs": "SGML",' + #13#10 + ' "GlossTerm": "Standard Generalized Markup Language",' + #13#10 + ' "Acronym": "SGML",' + #13#10 + ' "Abbrev": "ISO 8879:1986",' + #13#10 + ' "GlossDef": {' + #13#10 + '"para": "A meta-markup language, used to create markup languages such as DocBook.",' + #13#10 + ' "GlossSeeAlso": ["咏南中间件", "XML"]' + #13#10 + '},' + #13#10 + ' "GlossSee": "markup"' + #13#10 + '}' + #13#10 + '}' + #13#10 + '}' + #13#10 + '}' + #13#10 + '}'; type // 记录 TGlossary = record glossary: record title: string; GlossDiv: record title: string; GlossList: record GlossEntry: record ID, SortAs, GlossTerm, Acronym, Abbrev: string; GlossDef: record para: string; GlossSeeAlso: array of string; end; GlossSee: string; end; end; end; end; end; procedure TForm1.Button1Click(Sender: TObject); var gloss: TGlossary; json: RawUTF8; begin json := JSON1; RecordLoadJSON(gloss, @json[1], TypeInfo(TGlossary)); Memo1.Clear; Memo1.Lines.Add(gloss.glossary.title); // 中国 Memo1.Lines.Add(gloss.glossary.GlossDiv.title); // 湖南省 Memo1.Lines.Add(gloss.glossary.GlossDiv.GlossList.GlossEntry.ID); // 湘乡市 Memo1.Lines.Add(gloss.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso[0]); // 咏南中间件 end;
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值