通过 XML 解析 json

我真的不明白如何使用 Go 解析来自 Api 的响应,因为我首先看到的是 XML,然后是 Json:


<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://www.zzap.ru/">{"error":"","class_man":"MITSUBISHI","logopath":"https://koj.blob.core.windows.net/zzap-upload/upload/logos/se12d7724469c1dbbe07e303ac6e91b48.png","partnumber":"MR245368","class_cat":"windscreen washer motor","imagepath":"","code_cat":1116901944,"class_cur":"р.","price_count_instock":24,"price_min_instock":200.0,"price_avg_instock":810.0,"price_max_instock":1380.0,"price_count_order":457,"price_min_order":201.0,"price_avg_order":1079.0,"price_max_order":8004.0,"imagepathV2":[""],"code_man":3113}</string>

json


慕神8447489
浏览 125回答 1
1回答

胡子哥哥

以下代码将xml首先解组,然后解组被解组json的Text字段中struct的xml。下面是指向 Playground 的链接,您可以在其中运行示例并使用它。package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log")type xmlStructure struct {&nbsp; &nbsp; XMLName xml.Name `xml:"string"`&nbsp; &nbsp; Text&nbsp; &nbsp; string&nbsp; &nbsp;`xml:",chardata"`&nbsp; &nbsp; XMLNS&nbsp; &nbsp;string&nbsp; &nbsp;`xml:"xmlns,attr"`}type jsonStructure struct {&nbsp; &nbsp; Error&nbsp; &nbsp; &nbsp; string `json:"error"`&nbsp; &nbsp; ClassMan&nbsp; &nbsp;string `json:"class_man"`&nbsp; &nbsp; LogoPath&nbsp; &nbsp;string `json:"logo_path"`&nbsp; &nbsp; PartNumber string `json:"part_number"`&nbsp; &nbsp; ClassCat&nbsp; &nbsp;string `json:"class_cat"`&nbsp; &nbsp; // etc.}func main() {&nbsp; &nbsp; var input = `<?xml version="1.0" encoding="utf-8"?><string xmlns="http://www.zzap.ru/">{"error":"","class_man":"MITSUBISHI","logopath":"https://koj.blob.core.windows.net/zzap-upload/upload/logos/se12d7724469c1dbbe07e303ac6e91b48.png","partnumber":"MR245368","class_cat":"windscreen washer motor","imagepath":"","code_cat":1116901944,"class_cur":"р.","price_count_instock":24,"price_min_instock":200.0,"price_avg_instock":810.0,"price_max_instock":1380.0,"price_count_order":457,"price_min_order":201.0,"price_avg_order":1079.0,"price_max_order":8004.0,"imagepathV2":[""],"code_man":3113}</string>`&nbsp; &nbsp; var in xmlStructure&nbsp; &nbsp; if err := xml.Unmarshal([]byte(input), &in); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; var msg jsonStructure&nbsp; &nbsp; if err := json.Unmarshal([]byte(in.Text), &msg); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("%+v", msg)}去游乐场注意:该jsonStructure类型仍然缺少您示例中的某些字段。注2:由于您是 Go 新手:问题的关键在于struct字段后面的xml和json标签。它们必须与您获得的 xml/json 输入的字段名称相匹配。对于 xml,有一些特殊情况,例如将xml.Name结构与 xml 标签匹配所需的类型。(通过这种方式,整个xmlStructure结构与string输入中的标签匹配。)xml:"xmlns,attr"该字段的后面还告诉 xml 包查找标签中XMLNS调用的属性xmlns。string中缺少的名称xml:",chardata"告诉 xml 选择string标签的内容。标签更简单,仅在json输入中说明匹配的名称。另请注意,结构的字段本身必须导出,否则 xml/json 包无法访问它们并且无法填充。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go