XML 转 Json
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
)
type Persons struct {
Person []struct {
Name string
Age int
}
}
type Places struct {
Place []struct {
Name string
Country string
}
}
type Parks struct {
Park struct {
Name []string
Capacity []int
}
}
const personXml = `
<Persons>
<Person><Name>Koti</Name><Age>30</Age></Person>
<Person><Name>Kanna</Name><Age>29</Age></Person>
</Persons>
`
const placeXml = `
<Places>
<Place><Name>Chennai</Name><Country>India</Country></Place>
<Place><Name>London</Name><Country>UK</Country></Place>
</Places>
`
const parkXml = `
<Parks>
<Park><Name>National Park</Name><Capacity>10000</Capacity></Park>
<Park>Asian Park</Name><Capacity>20000</Capacity></Park>
</Parks>
`
func WhatIamUsing() {
var persons Persons
xml.Unmarshal([]byte(personXml), &persons)
per, _ := json.Marshal(persons)
fmt.Printf("%s\n", per)
var places Places
xml.Unmarshal([]byte(placeXml), &places)
pla, _ := json.Marshal(places)
fmt.Printf("%s\n", pla)
var parks Parks
xml.Unmarshal([]byte(parkXml), &parks)
par, _ := json.Marshal(parks)
fmt.Printf("%s\n", par)
}
我想要的是一个通用函数,它接受 xml 字符串和 dataStruct 并返回一个 Json 输出。但是下面的函数抛出一个错误如何暗示这个?
func Xml2Json(xmlString string, DataStruct interface{}) (jsobj string, err error) {
var dataStruct DataStruct
xml.Unmarshal([]byte(personXml), &dataStruct)
js, _ := json.Marshal(dataStruct)
return fmt.Sprintf("%s\n", js), nil
}
func main() {
jsonstring, _ := Xml2Json(personXml, Persons)
}
错误信息:
prog.go:73:DataStruct 不是类型
prog.go:80:类型 Persons 不是表达式
goplay 链接:http ://play.golang.org/p/vayb0bawKx