您的位置:首页 > Web前端 > JavaScript

Go进阶(7): JSON 序列化和反序列化

2019-08-25 11:47 603 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/shenziheng1/article/details/100060842

1. json序列化和反序列化基础

json数据的序列化和反序列化是一种非常常见的方式,尤其是在http/rcp的微服务调试中。

  • 基础语法

在 Go 中我们主要使用官方的 encoding/json 包对 JSON 数据进行序列化和反序列化,主要使用方法有:

[code]// 序列化
func Marshal(v interface{}) ([]byte, error)
// 反序列化
func Unmarshal ([]byte(data), &value)(error)
  • json与go数据类型对照表
类型 JSON Go
bool true, false true, false
string "a" string("a")
整数 1 int(1), int32(1), int64(1) ...
浮点数 3.14 float32(3.14), float64(3.14) ...
数组 [1,2] [2]int{1,2}, []int{1, 2}
对象 Object {"a": "b"} map[string]string, struct
未知类型 ... interface{}
  • 函数语法示例:
[code]package main

import (
"encoding/json"
"fmt"
)

func main(){
var (
data  = `1`
value int
)
err := json.Unmarshal([]byte(data), &value)
fmt.Println("Unmarshal error is : ", err)
fmt.Printf("Unmarshal value is %T, %d \n", value, value)

value2, err2 := json.Marshal(value)
fmt.Println("Marshal error is : ", err2)
fmt.Printf("Marshal value is %s \n", string(value2))
}

运行结果:

Unmarshal error is :  <nil>
Unmarshal value is int, 1
Marshal error is :  <nil>
Marshal value is 1

Note:在实际应用中,在序列化和反序列化的时候,需要检查函数返回的 err, 如果 err 不为空,表示数据转化失败。 例如:把上面例子中 value 类型由 int 修改为 string 后再次运行代码,你将得到 Unmarshal error is: json: cannot unmarshal number into Go value of type string 的错误提醒。

  • 不同数据类型序列化/反序列化示例:
[code]package main

import (
"encoding/json"
"fmt"
)

func main(){
var(
data1 = `false`
value1 bool
)
json.Unmarshal([]byte(data1), &value1)
printHelper("data1", value1)

var(
data2 = `3.1415926`
value2 float32
)
json.Unmarshal([]byte(data2), &value2)
printHelper("data2", value2)

var(
data3 = `[1,2,3,4,5]`
value3 []int
)
json.Unmarshal([]byte(data3), &value3)
printHelper("data3", value3)

var (
data4 = `{"name": "shenziheng", "school":"cornell university"}`
value4 map[string]string
value44 interface{}
)
json.Unmarshal([]byte(data4), &value4)
printHelper("data4",value4)

json.Unmarshal([]byte(data4), &value44)
printHelper("data4", value44)
}

func printHelper(name string, value interface{}){
fmt.Printf("%s Ummarshal type=%T, value=%v \n", name, value, value)
}

运行结果:

C:\Users\shenc\Go\src\JSON2>go run main.go
data1 Ummarshal type=bool, value=false
data2 Ummarshal type=float32, value=3.1415925
data3 Ummarshal type=[]int, value=[1 2 3 4 5]
data4 Ummarshal type=map[string]string, value=map[name:shenziheng school:cornell university]
data4 Ummarshal type=map[string]interface {}, value=map[name:shenziheng school:cornell university]

  • 自定义数据类型

除了使用基础数据外,对于那些比较复杂的数据集合(Object),还可以使用自定义数据类型 struct 来转化。只要规则有三条:

  1. Go 中关于 JSON 转化字段名的对应语法为:Field int `json:"myName"`
  2. 忽略空值的字段,使用 omitempty 选项:Field int `json:"myName,omitempty"`
  3. 忽略特定字段:Field int `json:"-"`

2. json序列化和反序列化进阶:复杂数据类型

  • 学生信息成绩单:
[code]{
"id":2019940606,
"name":"shenziheng",
"results" : {
"mathmatic school": {
"roi": "mathematic",
"score": "A"
},
"conputer school": {
"roi": "computer",
"score": "A+"
}
}
}

示例代码:

[code]package main

import (
"encoding/json"
"fmt"
"io/ioutil"
)

type Result struct{
ROI string `json:"roi"`
Score string `json:"score"`
}

type StudentInfo struct {
Id int `json:"id"`
Name string `json:"name"`
Results interface{} `json:"results"`
}

func main(){
data, _ := ioutil.ReadFile("studentInfo.json")

var student StudentInfo
json.Unmarshal(data, &student)
fmt.Printf("Students infomation is %v \n", student)

fmt.Printf("Students result is %T , %v \n", student.Results, student.Results)
res := student.Results
for index, value := range res.(map[string]interface{}) {
fmt.Printf("Students infomation is Index=%v, value=%v\n", index,value)
}
}

输出结果:

Students infomation is {2019940606 shenziheng map[conputer school:map[roi:computer score:A+] mathmatic school : map[roi:mathematic score:A]]}
Students result is map[string]interface {} , map[conputer school:map[roi:computer score:A+] mathmatic school:map[roi:ma
thematic score:A]]
Students infomation is Index=mathmatic school, value=map[roi:mathematic score:A]
Students infomation is Index=conputer school, value=map[roi:computer score:A+]

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: