【发布时间】:2014-09-16 22:45:06
【问题描述】:
有没有办法在 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", "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 包
【问题讨论】:
-
@DewyBroto 我已经放入 XML 响应
-
要直接使用
encoding/xml和encoding/json,您需要创建structs 以镜像XML 响应的格式。使用maps 可能有办法解决这个问题,但我不知道。 -
当我尝试
fmt.Print(&usr.userName)时,它会向控制台输出 nil -
啊,我对
encoding/xml了解不多,但我知道它不能写入小写字段(你的包之外的任何东西都不能)。我不知道你是怎么做映射的,但是如果你想研究的话,Unmarshal映射规则在golang.org/pkg/encoding/xml/#Unmarshal。 -
@DewyBroto 是的。我将 XML 输入作为字符串输入,因为它是直接从客户端 Javascript 接收的。