1. json字符串解析: json.Unmarshal(b, &f)
- json字符串解析到结构体中:
package main
import (
"encoding/json"
"fmt"
)
type Server struct {
ServerName string
ServerIP string
}
type Serverslice struct {
Servers []Server
}
func main() {
var s Serverslice
str := `{"servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
err := json.Unmarshal([]byte(str), &s)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%T, %v \n", s, s)
for _, item := range s.Servers {
fmt.Println(item)
}
}
}
输出结果:
main.Serverslice, {[{Shanghai_VPN 127.0.0.1} {Beijing_VPN 127.0.0.2}]}
{Shanghai_VPN 127.0.0.1}
{Beijing_VPN 127.0.0.2}
- json字符串直接解析到map中:
package main
import (
"encoding/json"
"fmt"
)
func main() {
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f map[string]interface{}
err := json.Unmarshal(b, &f)
if err != nil {
fmt.Println(err)
}
fmt.Printf("type: %T, value: %v\n", f["Age"], f["Age"])
fmt.Printf("type: %T, value: %v\n", f["Parents"], f["Parents"])
}
输出:
type: float64, value: 6
type: []interface {}, value: [Gomez Morticia]
2.生产Json:json.Marshal(s)
- 结构体转json
package main
import (
"encoding/json"
"fmt"
)
type Server struct {
ServerName string
ServerIP string
}
type Serverslice struct {
Servers []Server
}
func main() {
var s Serverslice
s.Servers = append(s.Servers, Server{ServerName: "Shanghai_VPN", ServerIP: "127.0.0.1"})
s.Servers = append(s.Servers, Server{ServerName: "Beijing_VPN", ServerIP: "127.0.0.2"})
b, err := json.Marshal(s)
if err != nil {
fmt.Println("json err:", err)
}
fmt.Println(string(b))
}
输出:
{"Servers":[{"ServerName":"Shanghai_VPN","ServerIP":"127.0.0.1"},{"ServerName":"Beijing_VPN","ServerIP":"127.0.0.2"}]}
- map直接转json
package main
import (
"encoding/json"
"fmt"
)
func main() {
var m = map[string]interface{} {"age":20, "name":"lili", "gender":"女"}
b, err := json.Marshal(m)
if err != nil {
fmt.Println("json err:", err)
}
fmt.Println(string(b))
}
输出:
{"age":20,"gender":"女","name":"lili"}
有疑问加站长微信联系(非本文作者)