-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11_WorkingWithXML_JSON.go
75 lines (66 loc) · 1.41 KB
/
11_WorkingWithXML_JSON.go
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"os"
)
type Person struct {
Name string `json:"fullname,omitempty"`
Age int
Job struct {
Department string
Title string
}
}
/*
- empty interface -> map
- tags for json
*/
type Address struct {
City, State string
}
type Person2 struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
func main() {
p1 := &Person{
Name: "Vasya",
Age: 36,
Job: struct {
Department string
Title string
}{Department: "Operations", Title: "Boss"},
}
j, err := json.Marshal(p1)
if err != nil {
fmt.Printf("%v\n", err)
return
}
fmt.Printf("p1 json %s\n", j)
var p2 Person
json.Unmarshal(j, &p2)
fmt.Printf("p2: %v\n", p2)
j = []byte(`{"Name":"Vasya", "Job":{"Department":"Operations","Title":"Boss"}}`)
var p3 interface{}
json.Unmarshal(j, &p3)
fmt.Printf("p3: %v\n", p3)
person, ok := p3.(map[string]interface{})
if ok {
fmt.Printf("name=%s\n", person["Name"])
}
v := &Person2{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
enc := xml.NewEncoder(os.Stdout)
enc.Indent(" ", " ")
enc.Encode(v)
}