有没有办法在 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 包
最佳答案
关于如何将 XML 输入转换为 JSON 输出的问题的一般答案可能是这样的:
http://play.golang.org/p/7HNLEUnX-m
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
)
type DataFormat struct {
ProductList []struct {
Sku string `xml:"sku" json:"sku"`
Quantity int `xml:"quantity" json:"quantity"`
} `xml:"Product" json:"products"`
}
func main() {
xmlData := []byte(`<?xml version="1.0" encoding="UTF-8" ?>
<ProductList>
<Product>
<sku>ABC123</sku>
<quantity>2</quantity>
</Product>
<Product>
<sku>ABC123</sku>
<quantity>2</quantity>
</Product>
</ProductList>`)
data := &DataFormat{}
err := xml.Unmarshal(xmlData, data)
if nil != err {
fmt.Println("Error unmarshalling from XML", err)
return
}
result, err := json.Marshal(data)
if nil != err {
fmt.Println("Error marshalling to JSON", err)
return
}
fmt.Printf("%s\n", result)
}
关于xml - 如何在 Golang 中将 []byte XML 转换为 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25879570/