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

5

有没有一种方法可以在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响应。 - Passionate Engineer
1
要以直接的方式使用encoding/xmlencoding/json,您需要创建与XML响应格式相对应的结构体。可能有使用map绕过此问题的方法,但我不知道。 - twotwotwo
当我尝试使用fmt.Print(&usr.userName)时,它会在控制台输出nil。 - Passionate Engineer
哦,关于 encoding/xml 我不是很了解,但我知道它无法写入小写字段(除了您的包外,任何东西都不能)。我不知道你是如何进行映射的,但如果您想要研究,Unmarshal 的映射规则可以在 http://golang.org/pkg/encoding/xml/#Unmarshal 找到。 - twotwotwo
@DewyBroto 是的。我将XML输入作为字符串输入,因为它直接从客户端JavaScript接收。 - Passionate Engineer
2个回答

13

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

11
如果您需要将一个具有未知结构的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 ...
}

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

1
修复示例:(这个工作正常)func main() { // xml 是一个 io.Reader xml := strings.NewReader(<?xml version="1.0" encoding="UTF-8"?><hello>world</hello>) json, err := xj.Convert(xml) if err != nil { panic("非常尴尬...") } fmt.Println(json.String()) // {"hello": "world"} } - luizfelipetx
@luizfelipetx 谢谢,我已经修复了代码片段。 - basgys
谢谢,但是我该如何去掉某些属性前面的负号? - iamatsundere181
嗨@basgys,有没有办法从json输出中删除带有“-”的字段。 - Avinash
嗨@iamatsundere181,你找到你问题的答案了吗? - Avinash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接