日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > javascript >内容正文

javascript

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

發(fā)布時(shí)間:2025/3/15 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Go进阶(7): JSON 序列化和反序列化 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1. json序列化和反序列化基礎(chǔ)

json數(shù)據(jù)的序列化和反序列化是一種非常常見的方式,尤其是在http/rcp的微服務(wù)調(diào)試中。

  • 基礎(chǔ)語(yǔ)法

在 Go 中我們主要使用官方的?encoding/json?包對(duì) JSON 數(shù)據(jù)進(jìn)行序列化和反序列化,主要使用方法有:

// 序列化 func Marshal(v interface{}) ([]byte, error) // 反序列化 func Unmarshal ([]byte(data), &value)(error)
  • json與go數(shù)據(jù)類型對(duì)照表
類型JSONGo
booltrue, falsetrue, false
string"a"string("a")
整數(shù)1int(1), int32(1), int64(1) ...
浮點(diǎn)數(shù)3.14float32(3.14), float64(3.14) ...
數(shù)組[1,2][2]int{1,2}, []int{1, 2}
對(duì)象 Object{"a": "b"}map[string]string, struct
未知類型...interface{}
  • 函數(shù)語(yǔ)法示例:
package mainimport ("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)) }

運(yùn)行結(jié)果:

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

Note:在實(shí)際應(yīng)用中,在序列化和反序列化的時(shí)候,需要檢查函數(shù)返回的 err, 如果 err 不為空,表示數(shù)據(jù)轉(zhuǎn)化失敗。 例如:把上面例子中 value 類型由 int 修改為 string 后再次運(yùn)行代碼,你將得到 Unmarshal error is: json: cannot unmarshal number into Go value of type string 的錯(cuò)誤提醒。

  • 不同數(shù)據(jù)類型序列化/反序列化示例:
package mainimport ("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]stringvalue44 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) }

運(yùn)行結(jié)果:

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]

  • 自定義數(shù)據(jù)類型

除了使用基礎(chǔ)數(shù)據(jù)外,對(duì)于那些比較復(fù)雜的數(shù)據(jù)集合(Object),還可以使用自定義數(shù)據(jù)類型 struct 來轉(zhuǎn)化。只要規(guī)則有三條:

  • Go 中關(guān)于 JSON 轉(zhuǎn)化字段名的對(duì)應(yīng)語(yǔ)法為:Field int `json:"myName"`
  • 忽略空值的字段,使用 omitempty 選項(xiàng):Field int `json:"myName,omitempty"`
  • 忽略特定字段:Field int `json:"-"`
  • 2. json序列化和反序列化進(jìn)階:復(fù)雜數(shù)據(jù)類型

    • 學(xué)生信息成績(jī)單:
    {"id":2019940606,"name":"shenziheng","results" : {"mathmatic school": {"roi": "mathematic","score": "A"},"conputer school": {"roi": "computer","score": "A+"}} }

    示例代碼:

    package mainimport ("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 StudentInfojson.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.Resultsfor index, value := range res.(map[string]interface{}) {fmt.Printf("Students infomation is Index=%v, value=%v\n", index,value)} }

    輸出結(jié)果:

    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+]

    總結(jié)

    以上是生活随笔為你收集整理的Go进阶(7): JSON 序列化和反序列化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。