第十章 json操作
目录一、Marshal 序列化
package main
import (
"encoding/json"
"fmt"
)
type Animal struct {
Name string `json:"name"`
Order string `json:"order"`
}
func main() {
var animals []Animal
animals = append(animals, Animal{Name: "Platypus", Order: "Monotremata"})
animals = append(animals, Animal{Name: "Quoll", Order: "Dasyuromorphia"})
jsonStr, err := json.Marshal(animals) // 也就是将可以转化成json的数据,进行json转换
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(jsonStr)) // [{"name":"Platypus","order":"Monotremata"},{"name":"Quoll","order":"Dasyuromorphia"}]
}
不写tag也可以,使用tag起一个别名也好⛱️。
二、Unmarshal 反序列化
1 已知数据解析
package main
import (
"encoding/json"
"fmt"
)
type Animal struct {
Name string
Order string
}
func main() {
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
}
2 未知数据解析
var f interface{}
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
json.Unmarshal(b, &f)
for k, v := range f.(map[string]interface{}) {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int ", vv)
case float64:
fmt.Println(k, "is float64 ", vv)
case []interface{}:
fmt.Println(k, "is array:")
for i, j := range vv {
fmt.Println(i, j)
}
}
}
3 json测试
package main
import (
"encoding/json"
"fmt"
)
type Base struct {
Name string `json:"name"`
Age int `json:"age"`
Hobby []string `json:"hobby"`
}
type Person struct {
BaseInfo Base
ID string
}
func main() {
person := Person{BaseInfo: Base{"yangyi", 18, []string{"sing", "song"}}, ID: "123456789"}
// 1 转化成json字符串
jsonStr, err := json.Marshal(person)
if err != nil {
fmt.Println("json转换成功...")
}
fmt.Println(string(jsonStr)) // {"BaseInfo":{"Name":"yangyi","Age":18,"Hobby":["sing","song"]},"ID":"123456789"}
// 2 json字符串反解析
var person1 Person
err = json.Unmarshal(jsonStr, &person1)
if err != nil {
fmt.Println("json字符串解析失败...")
}
fmt.Printf("%T\n", person1) // main.Person
fmt.Println(person1.BaseInfo.Hobby) // [sing song]
}
标签:animals,string,err,第九章,fmt,json,Println,操作
From: https://www.cnblogs.com/yangyi215/p/17284393.html