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

前端之家收集整理的这篇文章主要介绍了如何在Golang中将[]字节XM​​L转换为JSON输出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法在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",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,则可以使用 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 ...
}

Note : I’m the author of this library.

猜你在找的Go相关文章