有没有办法在Golang中将XML([] byte)转换为JSON输出?
我有下面的功能在哪里body,[]byte但我想经过一些操作后将此XML响应转换为JSON。我已经尝试Unmarshal过xml打包但没有成功:
body
[]byte
Unmarshal
xml
// POST func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) { App := new(Api) App.url = "http://api.com/api" usr := new(User) err := request.ReadEntity(usr) if err != nil { response.AddHeader("Content-Type", "application/json") response.WriteErrorString(http.StatusInternalServerError, err.Error()) return } buf := []byte("<app version=\"1.0\"><request>1111</request></app>") r, err := http.Post(App.url, "text/plain", bytes.NewBuffer(buf)) if err != nil { response.AddHeader("Content-Type", "application/json") response.WriteErrorString(http.StatusInternalServerError, err.Error()) return } defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) response.AddHeader("Content-Type", "application/json") response.WriteHeader(http.StatusCreated) // err = xml.Unmarshal(body, &usr) // if err != nil { // fmt.Printf("error: %v", err) // return // } response.Write(body) // fmt.Print(&usr.userName) }
我也在使用Go-restful软件包
如果需要使用未知结构将XML文档转换为JSON,则可以使用goxml2json。
范例:
import ( // Other imports ... xj "github.com/basgys/goxml2json" ) func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) { // Extract data from restful.Request xml := strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?><app version="1.0"><request>1111</request></app>`) // Convert json, err := xj.Convert(xml) if err != nil { // Oops... } // ... Use JSON ... }
注意:我是该库的作者。