有没有一种方法可以在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包
encoding/xml
和encoding/json
,您需要创建与XML响应格式相对应的结构体。可能有使用map
绕过此问题的方法,但我不知道。 - twotwotwofmt.Print(&usr.userName)
时,它会在控制台输出nil。 - Passionate Engineerencoding/xml
我不是很了解,但我知道它无法写入小写字段(除了您的包外,任何东西都不能)。我不知道你是如何进行映射的,但如果您想要研究,Unmarshal
的映射规则可以在 http://golang.org/pkg/encoding/xml/#Unmarshal 找到。 - twotwotwo