package main
import (
"encoding/json"
"fmt"
"os"
)
type Human2 struct {
Name string
Age int
Rmb float64
Gender bool
Hobbies []string
}
func NewHuman2(name string, age int,rmb float64,hobbies []string) *Human2 {
human := new(Human2)
human.Name = name
human.Age = age
human.Rmb = rmb
human.Hobbies = hobbies
return human
}
/*编码结构体,map,切片到JSON文件*/
func main061() {
dstFile, _ := os.OpenFile(`编码文件`, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
defer dstFile.Close()
encoder := json.NewEncoder(dstFile)
zqd := NewHuman2("张全蛋", 20,0.5,[]string{"抽烟", "喝酒","烫头"})
zld := NewHuman2("张lia蛋", 30,0.5,[]string{"抽烟", "喝酒","烫头"})
//dataMap := make(map[string]interface{})
//dataMap["title"] = "东契奇字母哥创历史当选月最佳"
//dataMap["date"] = "2019-12-04"
//dataMap["author"] = "至尊狗仔"
//dataMap["readers"] = 99999999
humans := make([]Human2, 0)
humans = append(humans, *zqd, *zld)
err := encoder.Encode(humans)
if err != nil{
fmt.Println("编码human到json文件失败,err=",err)
return
}
fmt.Println("编码human到json文件成功")
}
/*解码json文件为GO数据*/
func main() {
//打开要编码的文件
srcFile, _ := os.Open(`编码文件`)
defer srcFile.Close()
//创建于JSON结构想匹配的GO语言数据
//retSlice := make([]Human2,0)
retSlice := make([]map[string]interface{}, 0)
//创建JSON文件的解码器
decoder := json.NewDecoder(srcFile)
//解码文件数据到GO数据的地址中
err := decoder.Decode(&retSlice)
//检查错误
if err != nil{
fmt.Println("解码json文件失败,err=", err)
return
}
//打印结果
fmt.Println("解码成功",retSlice)
}
原文:https://www.cnblogs.com/yunweiqiang/p/11980694.html