这篇文章主要介绍Go语言中Json序列化反序列化及文件读写的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
概述
JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的、键值对的数据交换格式。结构由大括号'{}',中括号'[]',逗号',',冒号';',双引号'""'组成,包含的数据类型有Object,Number,Boolean,String,Array, NULL等。
JSON序列化
将Go语言原数据转换成JSON格式字符串
语法:
//传map,结构体,slice...,返回结果byte切片和error是否错误func Marshal(v interface{}) ([]byte, error)
结构体转JSON
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))}
map转JSON
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))}
切片转JSON
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反序列化
将JSON格式字符串转换成Go语言原数据
//传入JSON字符串的byte字节和Go接收数据的类型指针,返回err错误,是否返回成功func Unmarshal(data []byte, v interface{}) error
JSON转map
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)}
JSON转结构体
str:=`{"Name":"张三","Age":18,"Sex":30007,"Hobby":["听音乐","看书","打篮球"],"Money":18.62}`var p Personif err:=json.Unmarshal([]byte(str),&p);err!=nil{ fmt.Println("解码失败",err)}else{ fmt.Println("解析成功",p)}
JSON转切片
str:=`[{"Hobby":["听音乐","看书","打篮球"]}]`p:=make([]map[string]interface{}, 0)if err:=json.Unmarshal([]byte(str),&p);err!=nil{ fmt.Println("解码失败",err)}else{ fmt.Println("解析成功",p)}
写JSON文件
将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
map写入JSON文件
p:=make(map[string]interface{}, 0)p["name"]="张三"p["age"]=18p["sex"]='男'p["hobby"]=[]string{"听英语","看书"}p["money"]=15.63if 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("写入文件成功") }}
切片写入JSON文件
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文件
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文件
将json文件转换成Go语言源数据
//第一步 传文件的路径,返回文件的可读可写,error:是否成功func Open(name string) (*File, error)//第二步 传文件对象,返回一个从r读取的新解码器func NewDecoder(r io.Reader) *Decoder//第三步 解码器将值存储在v值中func (dec *Decoder) Decode(v interface{}) error
解码JSON文件为map
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) }}
解码JSON文件为切片
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) }}
解码JSON文件为结构体
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 mainimport ("encoding/json""fmt""os")type Person struct {Name string //姓名Age int //年龄Sex rune //性别Hobby []string //爱好Money float64 //钱}func main() {fmt.Println("---------------JSON序列化----------")//JSON序列化//结构体marshalStrut()//mapmarshalMap()//slicemarshalSlice()fmt.Println("\n", "---------------JSON反序列化----------", "\n")//JSON反序列化//mapunmarshalMap()//structunmarshalStruct()//sliceunmarshalSlice()fmt.Println("\n", "---------------写JSON文件----------", "\n")//结构体writeStructFile()//mapwriteMapFile()//slicewriteSliceFile()fmt.Println("\n", "---------------读JSON文件----------", "\n")//structreadStructFile()//mapreadMapFile()//slicereadSliceFile()}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 Personif 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)}}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"] = 18p["sex"] = '男'p["hobby"] = []string{"听英语", "看书"}p["money"] = 15.63if 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 文件成功")}}}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序列化反序列化及文件读写的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!