1. 程式人生 > 實用技巧 >golang 操作json

golang 操作json

goland中json的序列化和反序列化

轉換規則

golang中提供了標準庫來實現了json的處理,其對應的轉換規則如下

golang json
bool Boolean
int float Number
string string
struct object
array slice array
[]byte base64編碼後的JSON String
map Object, key必須是string
interface{} 按照內部實際進行轉換
nil NULL
channel complex function 不支援

轉換例項

package main

import (
	"encoding/json"
	"fmt"
)

type Json struct {
	Id     int
	Name   string `json:"name"`
	age    int
	Hobby  []string
	IsVip  bool
	Wight  int         `json:"wight,omitempty"`
	Height int         `json:"-"`
	Other  interface{} `json:"other"`
}

func main() {
	j := Json{
		Id:     2,
		Name:   "IVY",
		age:    10,
		Hobby:  []string{"code", "play"},
		IsVip:  true,
		Wight:  75,
		Height: 182,
		Other:  nil,
	}
	result, err := json.Marshal(j)

	if err != nil {
		fmt.Println(err)
	}
	// {"Id":2,"name":"IVY","Hobby":["code","play"],"IsVip":true,"wight":75,"other":null}
	fmt.Println(string(result))

	j2 := new(Json)

	err = json.Unmarshal(result, j2)
	if err != nil {
		fmt.Println(err)
	}
	// &{Id:2 Name:IVY age:0 Hobby:[code play] IsVip:true Wight:75 Height:0 Other:<nil>}
	fmt.Printf("%+v", j2)
}

json.Marshal: 將傳入的可json序列化的物件轉換為json

json.Unmarshal將合法的json轉為為golang的資料型別

json序列化合反序列化只會去轉換go物件的public屬性

jsonTag

json包轉換結構體的時候可以在結構體的tag上增加json的tag,json tag的值可以有多個,中間以逗號隔開

保留tag:保留的tag是json內部使用的

如果第一個引數不是保留tag,那麼這個引數將作為json序列化合反序列化時提取和輸出的key

omitempty: 保留tag,噹噹前的值為零值得時候忽略該欄位輸出和輸入

-: 保留tag,表示完全忽略輸入和輸出當前的欄位

第三方包

jsoniter:golang高效能的json序列化工具

安裝:go get github.com/json-iterator/go

無縫替換官方的encoding/json

  • 只需要在操作json的作用域內加上var json = jsoniter.ConfigCompatibleWithStandardLibrary即可替換官方的json包
package main

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
)

type Json struct {
	Id     int
	Name   string `json:"name"`
	age    int
	Hobby  []string
	IsVip  bool
	Wight  int         `json:"wight,omitempty"`
	Height int         `json:"-"`
	Other  interface{} `json:"other"`
}

func main() {
	var json = jsoniter.ConfigCompatibleWithStandardLibrary

	j := Json{
		Id:     2,
		Name:   "IVY",
		age:    10,
		Hobby:  []string{"code", "play"},
		IsVip:  true,
		Wight:  75,
		Height: 182,
		Other:  nil,
	}
	result, err := json.Marshal(j)

	if err != nil {
		fmt.Println(err)
	}
	// {"Id":2,"name":"IVY","Hobby":["code","play"],"IsVip":true,"wight":75,"other":null}
	fmt.Println(string(result))

	j2 := new(Json)

	err = json.Unmarshal(result, j2)
	if err != nil {
		fmt.Println(err)
	}
	// &{Id:2 Name:IVY age:0 Hobby:[code play] IsVip:true Wight:75 Height:0 Other:<nil>}
	fmt.Printf("%+v", j2)
}