【问题标题】:How to convert []byte XML to JSON output in Golang如何在 Golang 中将 []byte XML 转换为 JSON 输出
【发布时间】: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/xmlencoding/json,您需要创建structs 以镜像XML 响应的格式。使用maps 可能有办法解决这个问题,但我不知道。
  • 当我尝试fmt.Print(&amp;usr.userName) 时,它会向控制台输出 nil
  • 啊,我对encoding/xml 了解不多,但我知道它不能写入小写字段(你的包之外的任何东西都不能)。我不知道你是怎么做映射的,但是如果你想研究的话,Unmarshal 映射规则在golang.org/pkg/encoding/xml/#Unmarshal
  • @DewyBroto 是的。我将 XML 输入作为字符串输入,因为它是直接从客户端 Javascript 接收的。

标签: xml json go


【解决方案1】:

如果您需要将 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 ...
}

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

【讨论】:

  • 修复示例:(这很好用) func main() { // xml 是一个 io.Reader xml := strings.NewReader(&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;hello&gt;world&lt;/hello&gt;) json, err := xj.Convert(xml ) if err != nil { panic("这太尴尬了...") } fmt.Println(json.String()) // {"hello": "world"} }
  • @luizfelipetx 谢谢,我修复了 sn-p
  • tks,但是如何删除某些属性前面的减号?
【解决方案2】:

关于如何将 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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多