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:type Persons不是表达式
您不能在界面中存储类型(如人员).您可以将reflect.Type传递给您的函数.然后,你的调用看起来像Xml2Json(personXml,reflect.TypeOf(Persons)),这在我看来相当丑陋.
原文链接:https://www.f2er.com/go/186875.html更好的方法可能是:
func Xml2Json(xmlString string,value interface{}) (string,error) { if err := xml.Unmarshal([]byte(xmlString),value); err != nil { return "",err } js,err := json.Marshal(value) if err != nil { return "",err } return string(js),nil }
如果您对值本身不感兴趣,可以将此函数与Xml2Json(personXml,new(Persons))一起使用,并且
var persons Persons Xml2Json(personXML,&persons)
当您还想检索struct值以供以后处理时.