XML 到 Jsonpackage mainimport ( "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
2 回答
- 2 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消