Go实战--xml与json相互转换(The way to go)
来源:互联网 发布:前端自学软件 编辑:程序博客网 时间:2024/05/01 00:52
生命不止,继续 go go go !
之前写了两篇博客,分别介绍了go中的encoding/json和encoding/xml,有很多相识之处。
json和xml的恩恩怨怨还没有结束,在实战中我们会用到XML与json的相互转化,没有太难懂的地方。
xml转json
package mainimport ( "encoding/json" "encoding/xml" "fmt")type DataFormat struct { ProductList []struct { Sku string `xml:"sku" json:"sku"` Quantity int `xml:"quantity" json:"quantity"` } `xml:"Product" json:"products"`}func main() { xmlData := []byte(`<?xml version="1.0" encoding="UTF-8" ?><ProductList> <Product> <sku>ABC123</sku> <quantity>2</quantity> </Product> <Product> <sku>ABC123</sku> <quantity>2</quantity> </Product></ProductList>`) data := &DataFormat{} err := xml.Unmarshal(xmlData, data) if nil != err { fmt.Println("Error unmarshalling from XML", err) return } result, err := json.Marshal(data) if nil != err { fmt.Println("Error marshalling to JSON", err) return } fmt.Printf("%s\n", result)}
输出:
{“products”:[{“sku”:”ABC123”,”quantity”:2},{“sku”:”ABC123”,”quantity”:2}]}
xml文件转json文件
接下来,我们根据一个xml文件生产一个相应的json文件。
在src文件夹下mkdir xmlfile_to_jsonfile,新建一个一个XML文件:
Employees.xml
<?xml version="1.0"?> <company> <staff> <id>101</id> <firstname>Derek</firstname> <lastname>Young</lastname> <username>derekyoung</username> </staff> <staff> <id>102</id> <firstname>John</firstname> <lastname>Smith</lastname> <username>johnsmith</username> </staff> </company>
代码:
package main import ( "encoding/json" "encoding/xml" "fmt" "io/ioutil" "os" ) type jsonStaff struct { ID int FirstName string LastName string UserName string } type Staff struct { XMLName xml.Name `xml:"staff"` ID int `xml:"id"` FirstName string `xml:"firstname"` LastName string `xml:"lastname"` UserName string `xml:"username"` } type Company struct { XMLName xml.Name `xml:"company"` Staffs []Staff `xml:"staff"` } func (s Staff) String() string { return fmt.Sprintf("\t ID : %d - FirstName : %s - LastName : %s - UserName : %s \n", s.ID, s.FirstName, s.LastName, s.UserName) } func main() { xmlFile, err := os.Open("Employees.xml") if err != nil { fmt.Println("Error opening file:", err) return } defer xmlFile.Close() XMLdata, _ := ioutil.ReadAll(xmlFile) var c Company xml.Unmarshal(XMLdata, &c) // sanity check - XML level fmt.Println(c.Staffs) // convert to JSON var oneStaff jsonStaff var allStaffs []jsonStaff for _, value := range c.Staffs { oneStaff.ID = value.ID oneStaff.FirstName = value.FirstName oneStaff.LastName = value.LastName oneStaff.UserName = value.UserName allStaffs = append(allStaffs, oneStaff) } jsonData, err := json.Marshal(allStaffs) if err != nil { fmt.Println(err) os.Exit(1) } // sanity check - JSON level fmt.Println(string(jsonData)) // now write to JSON file jsonFile, err := os.Create("./Employees.json") if err != nil { fmt.Println(err) } defer jsonFile.Close() jsonFile.Write(jsonData) jsonFile.Close() }
生成了文件Employees.json :
[ { "ID": 101, "FirstName": "Derek", "LastName": "Young", "UserName": "derekyoung" }, { "ID": 102, "FirstName": "John", "LastName": "Smith", "UserName": "johnsmith" } ]
json转xml
type Person struct { Id int `xml:"id,attr"` FirstName string `xml:"name>first" json:"first"` LastName string `xml:"name>last" json:"last"`}func main() { j := `{"id": 10, "first": "firstname", "last":"lastname"}` var p Person fmt.Println(json.Unmarshal([]byte(j), &p), p) out, _ := xml.MarshalIndent(p, "\t", "\t") fmt.Println(string(out))}
2 0
- Go实战--xml与json相互转换(The way to go)
- Go实战--go中编码转换(The way to go)
- Go实战--go中使用libphonenumber(The way to go)
- Go实战--go中使用cookie(The way to go)
- Go实战--go中使用rpc(The way to go)
- Go实战--net/http中JSON的使用(The way to go)
- Go实战--golang新手入门常见错误(The way to go)
- Go实战--golang生成uuid(The way to go)
- The way to go !
- Go语言学习之encoding/xml(The way to go)
- Go实战--go语言中执行shell脚本(The way to go)
- Go实战--go语言操作sqlite数据库(The way to go)
- Go实战--go中使用google/protobuf(The way to go)
- Go实战--go中使用base64加密(The way to go)
- Go实战--go中使用hmac sha256(The way to go)
- Go实战--go中一些有用的代码片段(The way to go)
- Go实战--go中函数(function)和方法(method)的使用(The way to go)
- Go实战--go中函数递归(recursion)的使用(The way to go)
- hive中文乱码的解决办法
- LeetCode 96. Unique Binary Search Trees
- 腾讯云答治茜: CDN将进入智能计算时代
- Leetcode Week10
- 图片轮播/滚动
- Go实战--xml与json相互转换(The way to go)
- POJ1930_Dead Fraction_套公式法无限循环小数化分数
- 内存溢出和内存泄漏的区别
- 14届浙江省acm总结
- 一周电影榜20170502
- javascript深入理解js闭包
- C# 入门(4) 参数
- React:虚拟DOM
- Oracle-用户、角色以及权限控制