簡體   English   中英

如何在Golang中將[]字節XM​​L轉換為JSON輸出

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

有沒有辦法在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文檔轉換為具有未知結構的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 ...
}

注意:我是這個庫的作者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM