本文已参与「新人创作礼」活动,一起开启掘金创作之路。 @[TOC](Go语言 Jason)
概述
Json是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.
Json是在2001年开始推广使用的数据格式,目前已经成为主流的数据格式
JSON易于机器解析和生成,并有效地提升网络传输效率,通常程序在网络传输时会先将数据序列化成json字符串,到接收方得到json字符串时,在反序列化恢复成原来的 数据类型,这种方式已成为各个语言的标准
Json数据格式说明
JSON是以键值对来保存数据 其中值可以为列表,数组,字典,对象等
Json 序列化
介绍
json序列化是指,将有key-value结构的数据类型序列化成json字符串的操作
操作
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string
Age int
Score float64
Math int
}
func main() {
//结构体序列化
Struct()
//Map序列化
TestMap()
//切片序号化
TestSlice()
}
func TestSlice(){
var s [] map[string]interface{}
var Map map[string]interface{}
Map=make(map[string]interface{})
Map["name"]="李四"
Map["age"]=18
Map["address"]="中国"
s=append(s, Map)
var Map2 map[string]interface{}
Map2=make(map[string]interface{})
Map2["name"]="赵六"
Map2["age"]=20
Map2["address"]="北京"
s=append(s, Map2)
data,err:=json.Marshal(s)
if err!=nil{
fmt.Println("序列化错误 err=",err)
}
fmt.Println(string(data)) //[{"address":"中国","age":18,"name":"李四"},{"address":"北京","age":20,"name":"赵六"}]
}
func TestMap() {
var Map map[string]interface{}
Map=make(map[string]interface{})
Map["name"]="李四"
Map["age"]=18
Map["address"]="中国"
data,err:=json.Marshal(Map)
if err!=nil{
fmt.Println("序列化错误 err=",err)
}
fmt.Println(string(data)) //{"address":"中国","age":18,"name":"李四"}
}
func Struct(){
stu:=Student{
Name:"张三",
Age:18,
Score:95.0,
Math:99,
}
data,err:=json.Marshal(&stu)
if err!=nil{
fmt.Println("序列化错误 err=",err)
}
fmt.Println(string(data)) //{"Name":"张三","Age":18,"Score":95,"Math":99}
}
JSON 反序列化
介绍
将Json反序列化成对应的数据类型操作
操作
func Testunmarsha1struct() {
str:="{\"Name\":\"张三\",\"Age\":18,\"Score\":95,\"Math\":99}"
//定义一个Monster
var stu Student
err:=json.Unmarshal([]byte(str),&stu)
if err!=nil{
fmt.Println(err)
}
fmt.Println(stu)//{张三 18 95 99}
}