有没有办法在Golang中将XML([] byte)转换为JSON输出?
我有以下函数,其中body是[] byte但我想在一些操作之后将这个XML响应转换为JSON.我在xml包中尝试过Unmarshal但没有成功:
// 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",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.
原文链接:https://www.f2er.com/go/187013.html示例:
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 ... }
Note : I’m the author of this library.