Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Golang中将[]字节XML转换为JSON输出_Xml_Json_Go - Fatal编程技术网

如何在Golang中将[]字节XML转换为JSON输出

如何在Golang中将[]字节XML转换为JSON输出,xml,json,go,Xml,Json,Go,在Golang中有没有办法将XML([]字节)转换为JSON输出 我有下面的函数,其中body是[]字节,但我想在一些操作之后将这个XML响应转换为JSON。我在xml包中尝试了Unmarshal,但没有成功: // POST func (u *UserResource) authenticateUser(request *restful.Request, response *restful.Response) { App := new(Api) App.url = "http

在Golang中有没有办法将XML([]字节)转换为JSON输出

我有下面的函数,其中
body
[]字节
,但我想在一些操作之后将这个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)
}
//POST
func(u*UserResource)authenticateUser(请求*restful.request,响应*restful.response){
应用程序:=新(Api)
App.url=”http://api.com/api"
usr:=新(用户)
err:=request.ReadEntity(usr)
如果错误!=零{
AddHeader(“内容类型”、“应用程序/json”)
response.WriteErrorString(http.StatusInternalServerError,err.Error())
返回
}
buf:=[]字节(“1111”)
r、 err:=http.Post(App.url,“text/plain”,bytes.NewBuffer(buf))
如果错误!=零{
AddHeader(“内容类型”、“应用程序/json”)
response.WriteErrorString(http.StatusInternalServerError,err.Error())
返回
}
延迟r.Body.Close()
body,err:=ioutil.ReadAll(r.body)
AddHeader(“内容类型”、“应用程序/json”)
response.WriteHeader(http.StatusCreated)
//err=xml.Unmarshal(body和usr)
//如果错误!=零{
//fmt.Printf(“错误:%v”,错误)
//返回
//  }
响应。写入(正文)
//fmt.Print(&usr.userName)
}

我还使用了Go restful package

对于您关于如何将XML输入转换为JSON输出的问题,一般的答案可能是这样的:

主程序包
进口(
“编码/json”
“编码/xml”
“fmt”
)
类型DataFormat结构{
ProductList[]结构{
Sku字符串`xml:“Sku”json:“Sku”`
Quantity int`xml:“Quantity”json:“Quantity”`
}`xml:“产品”json:“产品”`
}
func main(){
xmlData:=[]字节(`
ABC123
2.
ABC123
2.
`)
数据:=&DataFormat{}
err:=xml.Unmarshal(xmlData,data)
如果为零!=错误{
Println(“从XML解组的错误”,err)
返回
}
结果,err:=json.Marshal(数据)
如果为零!=错误{
Println(“错误编组到JSON”,err)
返回
}
fmt.Printf(“%s\n”,结果)
}

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

例如:

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 ...
}
导入(
//其他进口。。。
xj“github.com/basgys/goxml2json”
)
func(u*UserResource)authenticateUser(请求*restful.request,响应*restful.response){
//从restful.Request中提取数据
xml:=strings.NewReader(`1111`)
//皈依
json,err:=xj.Convert(xml)
如果错误!=零{
//哎呀。。。
}
//…使用JSON。。。
}
注:我是这个图书馆的作者


@DewyBroto我在XML响应中加入了
encoding/XML
encoding/json
,对于它,您需要创建反映XML响应格式的
struct
s。使用
map
s可能有一些方法可以解决这个问题,但我不知道。当我尝试
fmt.Print(&usr.userName)
时,它会将nil输出到控制台,我不太了解
编码/xml
,但我知道它不能写入小写字段(包外的任何东西都不能)。我不知道你是如何进行映射的,但是如果你想研究的话,
Unmarshal
映射规则是可用的。@DewyBroto是的。我将XML输入作为一个字符串输入,因为它是直接从客户端Javascript接收的。修复示例:(这很好)func main(){//XML是一个io.Reader XML:=strings.NewReader(
world
)json,err:=xj.Convert(XML)if err!=nil{panic(“那很尴尬”)}fmt.Println(json.string()//{“你好”:“world”}@luizfelipetx谢谢,我修复了snippetk,但是如何删除某些属性前面的减号?
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 ...
}