golang gbk xml 解析后转json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main
import (
    "encoding/xml"
    "encoding/json"
    "log"
    "strings"
    simplejson "github.com/bitly/go-simplejson"
)
type Response struct {
    Status int `xml:"status" json:"status"`
}
func main() {
    
    var result Response
    //多行字符串,使用反引号`
    xmlstr := `<?xml version="1.0" encoding="GBK" ?>
<response>
    <status>200</status>
</response>`
    xmlstr = strings.Replace(xmlstr, "GBK", "UTF-8", -1)
    err := xml.Unmarshal([]byte(xmlstr), &result)
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("XML:%v",result)
    r, err := json.Marshal(result)
    if nil != err {
        log.Fatal(err)
    }
    log.Printf("JSON:%s", r)
    js, err := simplejson.NewJson([]byte(r))
    if nil != err {
        log.Fatal(err)
    }
    status, err := js.Get("status").Int()
    log.Printf("VALUE:%v",status)
}

输出:

1
2
3
2017/02/21 16:55:34 XML:{200}
2017/02/21 16:55:34 JSON:{"status":200}
2017/02/21 16:55:34 VALUE:200

本文网址: https://golangnote.com/topic/136.html 转摘请注明来源