golang中对json的序列化/反序列化操作还是比较容易的,
序列化操作主要是通过encoding/json包的Marshal()方法来实现,
反序列化操作主要是通过encoding/json包的Unmarshal()方法来实现.
1//JSON序列化和反序列化 2 3//可用在api序列化输出 4//转成结构体,方便程序操作等 5 6package main 7 8import ( 9 "encoding/json" 10 "fmt" 11) 12 13type Response1 struct { 14 Page int 15 Fruits []string 16} 17 18type Response2 struct { 19 Page int `json:"page"` 20 Fruits []string `json:"fruits"` 21} 22 23func main() { 24 25 //布尔型 26 boolByte, _ := json.Marshal(true) 27 fmt.Println(string(boolByte)) 28 29 //整数型 30 intByte, _ := json.Marshal(100) 31 fmt.Println(string(intByte)) 32 33 //浮点型 34 floatByte, _ := json.Marshal(1.23456) 35 fmt.Println(string(floatByte)) 36 37 //字符串 38 stringByte, _ := json.Marshal("字符串啊啊啊") 39 fmt.Println(string(stringByte)) 40 41 //切片 42 sliceByte, _ := json.Marshal([]string{"apple", "orange", "banana"}) 43 fmt.Println(string(sliceByte)) 44 45 //字典 46 mapByte, _ := json.Marshal(map[string]int{"apple": 5, "orange": 6, "banana": 7}) 47 fmt.Println(string(mapByte)) 48 49 //自定义类型1 50 customsByte1, _ := json.Marshal(&Response1{Page: 1, Fruits: []string{"apple", "orange", "banana"}}) 51 fmt.Println(string(customsByte1)) 52 53 //自定义类型2,tag语法 54 customsByte2, _ := json.Marshal(&Response2{Page: 2, Fruits: []string{"apple", "orange", "banana"}}) 55 fmt.Println(string(customsByte2)) 56 57 //反序列化到结构体 58 json1 := `{"Page":1,"Fruits":["apple","orange","banana"]}` 59 json2 := `{"page":2,"fruits":["apple","orange","banana"]}` 60 response1 := Response1{} 61 response2 := Response2{} 62 json.Unmarshal([]byte(json1), &response1) 63 fmt.Println(response1) 64 json.Unmarshal([]byte(json2), &response2) 65 fmt.Println(response2) 66}