这篇文章主要介绍Go语言中Json序列化反序列化及文件读写的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的、键值对的数据交换格式。结构由大括号'{}',中括号'[]',逗号',',冒号';',双引号'""'组成,包含的数据类型有Object,Number,Boolean,String,Array, NULL等。
将Go语言原数据转换成JSON格式字符串
语法:
//传map,结构体,slice...,返回结果byte切片和error是否错误 func Marshal(v interface{}) ([]byte, error)
type Person struct{ Name string //姓名 Age int //年龄 Sex rune //性别 Hobby []string //爱好 Money float64 //钱 } person:=Person{Name:"张三",Age:18,Sex:'男',Hobby:[]string{"听音乐","看书","打篮球"},Money:18.62} if bytes,err:=json.Marshal(person);err!=nil{ fmt.Println("编码错误",err) }else{ //{"Name":"张三","Age":18,"Sex":30007,"Hobby":["听音乐","看书","打篮球"],"Money":18.62} fmt.Println("编码成功:",string(bytes)) }
p:=make(map[string]interface{},0) p["0"]=map[string]interface{}{"name":"张三","age":18,"sex":'男',"hobby":[]string{"听音乐","看书","打篮球"},"money":18.62} p["1"]=map[string]interface{}{"name":"李四","age":19,"sex":'女',"hobby":[]string{"听音乐","看电影","打足球"},"money":1.62} if bytes,err:=json.Marshal(p);err!=nil{ fmt.Println("编码错误",err) }else{ fmt.Println(string(bytes)) }
p:=make([]map[string]interface{},0) p1:=map[string]interface{}{"name":"张三","age":18,"sex":'男',"hobby":[]string{"听音乐","看书","打篮球"},"money":18.62} p2:=map[string]interface{}{"name":"李四","age":19,"sex":'女',"hobby":[]string{"听音乐","看电影","打足球"},"money":1.62} p=append(p,p1,p2) if bytes,err:=json.Marshal(p);err!=nil{ fmt.Println("编码错误",err) }else{ fmt.Println(string(bytes)) }
将JSON格式字符串转换成Go语言原数据
//传入JSON字符串的byte字节和Go接收数据的类型指针,返回err错误,是否返回成功 func Unmarshal(data []byte, v interface{}) error
str:=`{"Name":"张三","Age":18,"Sex":30007,"Hobby":["听音乐","看书","打篮球"],"Money":18.62}` p:=make(map[string]interface{}, 0) if err:=json.Unmarshal([]byte(str),&p);err!=nil{ fmt.Println("解码失败",err) }else{ fmt.Println("解析成功",p) }
str:=`{"Name":"张三","Age":18,"Sex":30007,"Hobby":["听音乐","看书","打篮球"],"Money":18.62}` var p Person if err:=json.Unmarshal([]byte(str),&p);err!=nil{ fmt.Println("解码失败",err) }else{ fmt.Println("解析成功",p) }
str:=`[{"Hobby":["听音乐","看书","打篮球"]}]` p:=make([]map[string]interface{}, 0) if err:=json.Unmarshal([]byte(str),&p);err!=nil{ fmt.Println("解码失败",err) }else{ fmt.Println("解析成功",p) }
将Go语言源数据写入到json文件
//第一步 传文件的路径,返回文件的可读可写,error:是否成功 //flag:文件标识:是创建还是,追加...... //parm:文件模式表示文件的模式和权限位,通常,请求的模式为 0666,它使该文件可由任何人读和写 func OpenFile(name string, flag int, perm FileMode) (*File, error) 或者 func Create(name string) (*File, error) //传入文件的名字,返回文件的对象和error是否成功 //第二步 传文件对象,返回一个从w读取的新编码器 func NewEncoder(w io.Writer) *Encoder //第三步 编码器将v写入流中,后换行 func (enc *Encoder) Encode(v interface{}) error
p:=make(map[string]interface{}, 0) p["name"]="张三" p["age"]=18 p["sex"]='男' p["hobby"]=[]string{"听英语","看书"} p["money"]=15.63 if distFile,err:=os.OpenFile("map.json",os.O_CREATE,0666);err!=nil{ fmt.Println("创建文件失败",err) }else { enc:=json.NewEncoder(distFile) if err:=enc.Encode(p);err!=nil { fmt.Println("写入文件失败", err) }else{ fmt.Println("写入文件成功") } }
p:=make([]map[string]interface{}, 0) p1:=map[string]interface{}{"name":"张三","age":18,"sex":'男',"hobby":[]string{"听书","看电视"},"money":15.84} p2:=map[string]interface{}{"name":"李四","age":20,"sex":'女',"hobby":[]string{"打篮球","看书"},"money":125.84} p=append(p,p1,p2) if distFile,err:=os.OpenFile("slice.json",os.O_CREATE,0666);err!=nil{ fmt.Println("创建slice文件失败", err) }else { enc:=json.NewEncoder(distFile) if err:=enc.Encode(p);err!=nil{ fmt.Println("写入slice 文件失败", err) }else{ fmt.Println("写入slice 文件成功") } }
p:=Person{Name:"张三",Age:18,Sex:'男',Hobby:[]string{"听英语","读书"},Money:15.35} if distFile,err:=os.OpenFile("张三.json",os.O_CREATE|os.O_APPEND,0666);err!=nil{ fmt.Println("创建文件失败",err) }else{ enc:=json.NewEncoder(distFile) if err:=enc.Encode(&p);err!=nil { fmt.Println("写入文件失败",err) }else { fmt.Println("写入文件成功") } }
将json文件转换成Go语言源数据
//第一步 传文件的路径,返回文件的可读可写,error:是否成功 func Open(name string) (*File, error) //第二步 传文件对象,返回一个从r读取的新解码器 func NewDecoder(r io.Reader) *Decoder //第三步 解码器将值存储在v值中 func (dec *Decoder) Decode(v interface{}) error
p:=make(map[string]interface{}, 0) if srcFile,err:=os.Open("map.json");err!=nil{ fmt.Println("打开map 文件失败",err) }else{ en:=json.NewDecoder(srcFile) if err:=en.Decode(&p);err!=nil{ fmt.Println("读入map 文件失败",err) }else { fmt.Println("读取map 文件成功",p) } }
p:=make([]map[string]interface{}, 0) if srcFile,err:=os.Open("slice.json");err!=nil{ fmt.Println("打开slice 文件失败", err) }else{ en:=json.NewDecoder(srcFile) if err:=en.Decode(&p);err!=nil{ fmt.Println("读入slice 文件失败", err) }else { fmt.Println("读取slice 文件成功", p) } }
var p =new(Person) if srcFile,err:=os.Open("struct.json");err!=nil{ fmt.Println("打开struct 文件失败", err) }else{ en:=json.NewDecoder(srcFile) if err:=en.Decode(&p);err!=nil{ fmt.Println("读入struct 文件失败", err) }else{ fmt.Println("读取struct 文件成功", *p) } }
package main import ( "encoding/json" "fmt" "os" ) type Person struct { Name string //姓名 Age int //年龄 Sex rune //性别 Hobby []string //爱好 Money float64 //钱 } func main() { fmt.Println("---------------JSON序列化----------") //JSON序列化 //结构体 marshalStrut() //map marshalMap() //slice marshalSlice() fmt.Println("\n", "---------------JSON反序列化----------", "\n") //JSON反序列化 //map unmarshalMap() //struct unmarshalStruct() //slice unmarshalSlice() fmt.Println("\n", "---------------写JSON文件----------", "\n") //结构体 writeStructFile() //map writeMapFile() //slice writeSliceFile() fmt.Println("\n", "---------------读JSON文件----------", "\n") //struct readStructFile() //map readMapFile() //slice readSliceFile() } /************************序列化*********************/ func marshalStrut() { person := Person{Name: "张三", Age: 18, Sex: '男', Hobby: []string{"听音乐", "看书", "打篮球"}, Money: 18.62} if bytes, err := json.Marshal(person); err != nil { fmt.Println("结构体序列化错误", err) } else { //{"Name":"张三","Age":18,"Sex":30007,"Hobby":["听音乐","看书","打篮球"],"Money":18.62} fmt.Println("结构体序列化成功:", string(bytes)) } } func marshalMap() { p := make(map[string]interface{}, 0) p["0"] = map[string]interface{}{"name": "张三", "age": 18, "sex": '男', "hobby": []string{"听音乐", "看书", "打篮球"}, "money": 18.62} p["1"] = map[string]interface{}{"name": "李四", "age": 19, "sex": '女', "hobby": []string{"听音乐", "看电影", "打足球"}, "money": 1.62} if bytes, err := json.Marshal(p); err != nil { fmt.Println("map 序列化错误", err) } else { // {"0":{"age":18,"hobby":["听音乐","看书","打篮球"],"money":18.62,"name":"张三","sex":30007},"1":{"age":19,"hobby":["听音乐","看电影","打足球"],"money":1.62,"name":"李四","sex":22899}} fmt.Println("map 序列化成功", string(bytes)) } } func marshalSlice() { p := make([]map[string]interface{}, 0) p1 := map[string]interface{}{"name": "张三", "age": 18, "sex": '男', "hobby": []string{"听音乐", "看书", "打篮球"}, "money": 18.62} p2 := map[string]interface{}{"name": "李四", "age": 19, "sex": '女', "hobby": []string{"听音乐", "看电影", "打足球"}, "money": 1.62} p = append(p, p1, p2) if bytes, err := json.Marshal(p); err != nil { fmt.Println("slice 序列化错误", err) } else { // [{"age":18,"hobby":["听音乐","看书","打篮球"],"money":18.62,"name":"张三","sex":30007},{"age":19,"hobby":["听音乐","看电影","打足球"],"money":1.62,"name":"李四","sex":22899}] fmt.Println("slice 序列化成功", string(bytes)) } } /************************反序列化*********************/ func unmarshalMap() { str := `{"Name":"张三","Age":18,"Sex":30007,"Hobby":["听音乐","看书","打篮球"],"Money":18.62}` p := make(map[string]interface{}, 0) if err := json.Unmarshal([]byte(str), &p); err != nil { fmt.Println("map 反序列化失败", err) } else { //map[Age:18 Hobby:[听音乐 看书 打篮球] Money:18.62 Name:张三 Sex:30007] fmt.Println("map 反序列化成功", p) } } func unmarshalStruct() { str := `{"Name":"张三","Age":18,"Sex":30007,"Hobby":["听音乐","看书","打篮球"],"Money":18.62}` var p Person if err := json.Unmarshal([]byte(str), &p); err != nil { fmt.Println("struct 反序列化失败", err) } else { //{张三 18 30007 [听音乐 看书 打篮球] 18.62} fmt.Println("struct 反序列化成功", p) } } func unmarshalSlice() { str := `[{"Hobby":["听音乐","看书","打篮球"]},{"Hobby":["听书","看书","打足球"]}]` p := make([]map[string]interface{}, 0) if err := json.Unmarshal([]byte(str), &p); err != nil { fmt.Println("slice 反序列化失败", err) } else { // [map[Hobby:[听音乐 看书 打篮球]]] fmt.Println("slice 反序列化成功", p) } } /************************写JSON文件*********************/ func writeStructFile() { p := Person{Name: "张三", Age: 18, Sex: '男', Hobby: []string{"听英语", "读书"}, Money: 15.35} if distFile, err := os.OpenFile("struct.json", os.O_CREATE|os.O_TRUNC, 0666); err != nil { fmt.Println("创建struct文件失败", err) } else { enc := json.NewEncoder(distFile) if err := enc.Encode(&p); err != nil { fmt.Println("写入struct文件失败", err) } else { fmt.Println("写入struct文件成功") } } } func writeMapFile() { p := make(map[string]interface{}, 0) p["name"] = "张三" p["age"] = 18 p["sex"] = '男' p["hobby"] = []string{"听英语", "看书"} p["money"] = 15.63 if distFile, err := os.OpenFile("map.json", os.O_CREATE, 0666); err != nil { fmt.Println("创建map 文件失败", err) } else { enc := json.NewEncoder(distFile) if err := enc.Encode(p); err != nil { fmt.Println("写入map文件失败", err) } else { fmt.Println("写入map 文件成功") } } } func writeSliceFile() { p := make([]map[string]interface{}, 0) p1 := map[string]interface{}{"name": "张三", "age": 18, "sex": '男', "hobby": []string{"听书", "看电视"}, "money": 15.84} p2 := map[string]interface{}{"name": "李四", "age": 20, "sex": '女', "hobby": []string{"打篮球", "看书"}, "money": 125.84} p = append(p, p1, p2) if distFile, err := os.OpenFile("slice.json", os.O_CREATE, 0666); err != nil { fmt.Println("创建slice文件失败", err) } else { enc := json.NewEncoder(distFile) if err := enc.Encode(p); err != nil { fmt.Println("写入slice 文件失败", err) } else { fmt.Println("写入slice 文件成功") } } } /************************读JSON文件*********************/ func readStructFile() { var p = new(Person) if err := readFile("struct.json", "打开struct 文件失败", &p); err != nil { fmt.Println("读入struct 文件失败", err) } else { fmt.Println("读取struct 文件成功", *p) } } func readMapFile() { p := make(map[string]interface{}, 0) if err := readFile("map.json", "打开map 文件失败", &p); err != nil { fmt.Println("读取map 文件失败", err) } else { fmt.Println("读取map 文件成功", p) } } func readSliceFile() { p := make([]map[string]interface{}, 0) if err := readFile("slice.json", "打开slice 文件失败", &p); err != nil { fmt.Println("读入slice 文件失败", err) } else { fmt.Println("读取slice 文件成功", p) } } //封装 func readFile(f string, c string, v interface{}) error { if srcFile := openFile(f, c); srcFile != nil { en := json.NewDecoder(srcFile) if err := en.Decode(v); err != nil { return err } } return nil } func openFile(f string, c string) *os.File { if srcFile, err := os.Open(f); err != nil { fmt.Println(c, err) } else { return srcFile } return nil }
以上是“Go语言中Json序列化反序列化及文件读写的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。