-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
59 lines (44 loc) · 1.37 KB
/
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
package main
import (
"encoding/json"
"fmt"
)
type Profile struct {
Address string `json:"address"`
Phone string `json:"phone"`
}
type Person struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
Profile []Profile `json:"profiles"`
}
func main() {
fmt.Println("Learning Json")
profile1 := Profile{Address: "Dhaka", Phone: "017545544"}
profile2 := Profile{Address: "Barishal", Phone: "888888888"}
person := Person{Name: "Ruhul", Email: "[email protected]", Age: 25}
person.Profile = []Profile{profile1, profile2}
// Encoding to json
jsonString, err := json.Marshal(person)
if err != nil {
fmt.Println("Error Occur while encoding to json", err)
return
}
fmt.Println("Encoding JSON string", string(jsonString))
// Decoding Json DATA
var decodedData Person
err = json.Unmarshal(jsonString, &decodedData)
if err != nil {
fmt.Println("Error Occur while decoding to json", err)
}
fmt.Println("Decoded JSON string", decodedData)
// Decode static json string
var decodedData2 Person
staticString := `{"name":"Ruhul","email":"[email protected]","age":25,"profiles":[{"address":"Dhaka","phone":"017545544"},{"address":"Barishal","phone":"888888888"}]}`
err = json.Unmarshal([]byte(staticString), &decodedData2)
if err != nil {
return
}
fmt.Println("Decoded Static JSON string", decodedData2)
}