如何在Golang中将[]字节XM??L转换为JSON输出
发布时间:2020-12-16 19:20:59 所属栏目:大数据 来源:网络整理
导读:有没有办法在Golang中将XML([] byte)转换为JSON输出? 我有以下函数,其中body是[] byte但我想在一些操作之后将这个XML响应转换为JSON.我在xml包中尝试过Unmarshal但没有成功: // POST func (u *UserResource) authenticateUser(request *restful.Request,re
有没有办法在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.
示例: 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 ... }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |