如何在Golang中将[]byte类型的XML转换为JSON输出

huangapple go评论119阅读模式
英文:

How to convert []byte XML to JSON output in Golang

问题

在Golang中,有一种方法可以将XML([]byte)转换为JSON输出。您可以尝试使用encoding/xml包中的Unmarshal函数进行转换。以下是您提供的代码示例的修改版本:

  1. import (
  2. "encoding/xml"
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "bytes"
  7. "github.com/emicklei/go-restful"
  8. )
  9. // POST
  10. func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) {
  11. App := new(Api)
  12. App.url = "http://api.com/api"
  13. usr := new(User)
  14. err := request.ReadEntity(usr)
  15. if err != nil {
  16. response.AddHeader("Content-Type", "application/json")
  17. response.WriteErrorString(http.StatusInternalServerError, err.Error())
  18. return
  19. }
  20. buf := []byte("<app version=\"1.0\"><request>1111</request></app>")
  21. r, err := http.Post(App.url, "text/plain", bytes.NewBuffer(buf))
  22. if err != nil {
  23. response.AddHeader("Content-Type", "application/json")
  24. response.WriteErrorString(http.StatusInternalServerError, err.Error())
  25. return
  26. }
  27. defer r.Body.Close()
  28. body, err := ioutil.ReadAll(r.Body)
  29. if err != nil {
  30. response.AddHeader("Content-Type", "application/json")
  31. response.WriteErrorString(http.StatusInternalServerError, err.Error())
  32. return
  33. }
  34. // 将XML转换为JSON
  35. var result map[string]interface{}
  36. err = xml.Unmarshal(body, &result)
  37. if err != nil {
  38. response.AddHeader("Content-Type", "application/json")
  39. response.WriteErrorString(http.StatusInternalServerError, err.Error())
  40. return
  41. }
  42. // 将JSON转换为[]byte
  43. jsonData, err := json.Marshal(result)
  44. if err != nil {
  45. response.AddHeader("Content-Type", "application/json")
  46. response.WriteErrorString(http.StatusInternalServerError, err.Error())
  47. return
  48. }
  49. response.AddHeader("Content-Type", "application/json")
  50. response.WriteHeader(http.StatusCreated)
  51. response.Write(jsonData)
  52. }

以上代码将XML响应转换为JSON,并在进行一些操作后输出。您需要导入encoding/xmlencoding/json包,并对XML和JSON进行相应的解析和编码。

英文:

Is there a way to convert XML ([]byte) to JSON output in Golang?

I've got below function where body is []byte but I want to transform this XML response to JSON after some manipulation. I've tried Unmarshal in xml package with no success:

  1. // POST
  2. func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) {
  3. App := new(Api)
  4. App.url = &quot;http://api.com/api&quot;
  5. usr := new(User)
  6. err := request.ReadEntity(usr)
  7. if err != nil {
  8. response.AddHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)
  9. response.WriteErrorString(http.StatusInternalServerError, err.Error())
  10. return
  11. }
  12. buf := []byte(&quot;&lt;app version=\&quot;1.0\&quot;&gt;&lt;request&gt;1111&lt;/request&gt;&lt;/app&gt;&quot;)
  13. r, err := http.Post(App.url, &quot;text/plain&quot;, bytes.NewBuffer(buf))
  14. if err != nil {
  15. response.AddHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)
  16. response.WriteErrorString(http.StatusInternalServerError, err.Error())
  17. return
  18. }
  19. defer r.Body.Close()
  20. body, err := ioutil.ReadAll(r.Body)
  21. response.AddHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)
  22. response.WriteHeader(http.StatusCreated)
  23. // err = xml.Unmarshal(body, &amp;usr)
  24. // if err != nil {
  25. // fmt.Printf(&quot;error: %v&quot;, err)
  26. // return
  27. // }
  28. response.Write(body)
  29. // fmt.Print(&amp;usr.userName)
  30. }

I'm also using Go-restful package

答案1

得分: 13

将XML输入转换为JSON输出的通用答案可能如下所示:

  1. package main
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "fmt"
  6. )
  7. type DataFormat struct {
  8. ProductList []struct {
  9. Sku string `xml:"sku" json:"sku"`
  10. Quantity int `xml:"quantity" json:"quantity"`
  11. } `xml:"Product" json:"products"`
  12. }
  13. func main() {
  14. xmlData := []byte(`<?xml version="1.0" encoding="UTF-8"?>
  15. <ProductList>
  16. <Product>
  17. <sku>ABC123</sku>
  18. <quantity>2</quantity>
  19. </Product>
  20. <Product>
  21. <sku>ABC123</sku>
  22. <quantity>2</quantity>
  23. </Product>
  24. </ProductList>`)
  25. data := &DataFormat{}
  26. err := xml.Unmarshal(xmlData, data)
  27. if nil != err {
  28. fmt.Println("Error unmarshalling from XML", err)
  29. return
  30. }
  31. result, err := json.Marshal(data)
  32. if nil != err {
  33. fmt.Println("Error marshalling to JSON", err)
  34. return
  35. }
  36. fmt.Printf("%s\n", result)
  37. }

这段代码使用Go语言将XML数据解析为结构体,并将其转换为JSON格式。你可以将XML数据存储在xmlData变量中,然后通过xml.Unmarshal函数将其解析为DataFormat结构体。接下来,使用json.Marshal函数将结构体转换为JSON格式,并将结果打印出来。

英文:

The generic answer to your question of how to convert XML input to JSON output might be something like this:

http://play.golang.org/p/7HNLEUnX-m

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;encoding/xml&quot;
  5. &quot;fmt&quot;
  6. )
  7. type DataFormat struct {
  8. ProductList []struct {
  9. Sku string `xml:&quot;sku&quot; json:&quot;sku&quot;`
  10. Quantity int `xml:&quot;quantity&quot; json:&quot;quantity&quot;`
  11. } `xml:&quot;Product&quot; json:&quot;products&quot;`
  12. }
  13. func main() {
  14. xmlData := []byte(`&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
  15. &lt;ProductList&gt;
  16. &lt;Product&gt;
  17. &lt;sku&gt;ABC123&lt;/sku&gt;
  18. &lt;quantity&gt;2&lt;/quantity&gt;
  19. &lt;/Product&gt;
  20. &lt;Product&gt;
  21. &lt;sku&gt;ABC123&lt;/sku&gt;
  22. &lt;quantity&gt;2&lt;/quantity&gt;
  23. &lt;/Product&gt;
  24. &lt;/ProductList&gt;`)
  25. data := &amp;DataFormat{}
  26. err := xml.Unmarshal(xmlData, data)
  27. if nil != err {
  28. fmt.Println(&quot;Error unmarshalling from XML&quot;, err)
  29. return
  30. }
  31. result, err := json.Marshal(data)
  32. if nil != err {
  33. fmt.Println(&quot;Error marshalling to JSON&quot;, err)
  34. return
  35. }
  36. fmt.Printf(&quot;%s\n&quot;, result)
  37. }

答案2

得分: 11

如果您需要将一个具有未知结构的XML文档转换为JSON,您可以使用goxml2json

示例:

  1. import (
  2. // 其他导入...
  3. xj "github.com/basgys/goxml2json"
  4. )
  5. func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) {
  6. // 从restful.Request中提取数据
  7. xml := strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?><app version="1.0"><request>1111</request></app>`)
  8. // 转换
  9. json, err := xj.Convert(xml)
  10. if err != nil {
  11. // 出错了...
  12. }
  13. // ... 使用JSON ...
  14. }

注意:我是这个库的作者。

英文:

If you need to convert an XML document to JSON with an unknown struct, you can use goxml2json.

Example :

  1. import (
  2. // Other imports ...
  3. xj &quot;github.com/basgys/goxml2json&quot;
  4. )
  5. func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) {
  6. // Extract data from restful.Request
  7. xml := strings.NewReader(`&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;app version=&quot;1.0&quot;&gt;&lt;request&gt;1111&lt;/request&gt;&lt;/app&gt;`)
  8. // Convert
  9. json, err := xj.Convert(xml)
  10. if err != nil {
  11. // Oops...
  12. }
  13. // ... Use JSON ...
  14. }

> Note : I'm the author of this library.

huangapple
  • 本文由 发表于 2014年9月17日 06:45:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/25879570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定