xml - 如何在 Golang 中将 []byte XML 转换为 JSON 输出

标签 xml json go

有没有办法在 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/

相关文章:

java - Android 无法使用 attrs 值扩充布局文件

android - Android应用突然崩溃

git - 当 $PATH 中有多个 git 可用时, 'go get' 使用哪个 git 版本?

c# - 我如何使用 XmlDocument.Save() 将 ="us-ascii"编码为数字字符实体而不是问号?

java - 带有纯 JSON 的 Delphi XE7 Datasnap

python - 当字典的长度/顺序发生变化时,如何从字典列表中提取特定值

c# - 反序列化时无效的 JSON 原语

Golang 入站 channel 未在 goroutine 中接收

database - Postgres 驱动程序在 go 中找不到表

java - 使用 Java 阅读更多 RSS 提要