Golang中JSON与XML互转:对接第三方API需求实现
Go实现JSON与XML互转对接第三方API
核心思路
要完成「接收JSON转XML发第三方API、接收XML转JSON返回」的流程,关键是用Go标准库的encoding/json和encoding/xml包,通过结构体标签映射JSON与XML的字段对应关系,实现双向转换。
步骤1:定义匹配结构的结构体
根据给定的XML和JSON格式,定义带xml和json标签的结构体,确保字段一一对应:
package main import ( "bytes" "encoding/json" "encoding/xml" "fmt" "net/http" ) // AutoCreateRequest 对应XML根节点AutoCreate和JSON的AutoCreate字段 type AutoCreateRequest struct { XMLName xml.Name `xml:"AutoCreate" json:"AutoCreate"` Request RequestData `xml:"Request" json:"Request"` } // RequestData 对应嵌套的Request节点/字段 type RequestData struct { APIUsername string `xml:"APIUsername" json:"APIUsername"` APIPassword string `xml:"APIPassword" json:"APIPassword"` Method string `xml:"Method" json:"Method"` } // AutoCreateResponse 适配第三方API返回的XML结构(需根据实际返回调整) type AutoCreateResponse struct { XMLName xml.Name `xml:"AutoCreate"` Response ResponseData `xml:"Response"` } type ResponseData struct { Code string `xml:"Code" json:"Code"` Message string `xml:"Message" json:"Message"` // 其他返回字段按需添加 }
步骤2:实现完整转换与请求流程
接收传入的JSON,转XML发送到第三方API,再将返回的XML转JSON响应:
func proxyHandler(w http.ResponseWriter, r *http.Request) { // 1. 解析传入的JSON数据 var req AutoCreateRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, fmt.Sprintf("解析JSON失败: %v", err), http.StatusBadRequest) return } defer r.Body.Close() // 2. 将结构体转为XML(带缩进和声明) xmlBytes, err := xml.MarshalIndent(&req, "", " ") if err != nil { http.Error(w, fmt.Sprintf("转换XML失败: %v", err), http.StatusInternalServerError) return } xmlFull := []byte(xml.Header + string(xmlBytes)) // 补全XML声明 // 3. 发送XML到第三方API thirdPartyURL := "https://third-party-api.example.com/your-endpoint" apiResp, err := http.Post(thirdPartyURL, "application/xml", bytes.NewBuffer(xmlFull)) if err != nil { http.Error(w, fmt.Sprintf("请求第三方API失败: %v", err), http.StatusInternalServerError) return } defer apiResp.Body.Close() // 4. 解析API返回的XML var respData AutoCreateResponse if err := xml.NewDecoder(apiResp.Body).Decode(&respData); err != nil { http.Error(w, fmt.Sprintf("解析API返回XML失败: %v", err), http.StatusInternalServerError) return } // 5. 将结果转为JSON返回 w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(respData); err != nil { http.Error(w, fmt.Sprintf("转换JSON失败: %v", err), http.StatusInternalServerError) return } } func main() { http.HandleFunc("/api-proxy", proxyHandler) fmt.Println("服务启动在 :8080") http.ListenAndServe(":8080", nil) }
关键细节说明
- 结构体标签:
xml:"标签名"指定XML节点/元素名,json:"标签名"指定JSON字段名,确保转换时字段精准匹配。 - XML声明:
xml.Marshal默认不生成<?xml version="1.0" encoding="UTF-8"?>,手动拼接xml.Header补全,避免第三方API解析报错。 - 错误处理:每一步都做错误捕获并返回对应HTTP状态码,保证接口的健壮性。
- 响应结构调整:实际使用时需根据第三方API返回的XML结构,修改
AutoCreateResponse和ResponseData的字段及标签。
内容的提问来源于stack exchange,提问作者Joel Swakise TheDancer
相关产品推荐
相关产品推荐

