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.
public

jsonTag

json包转换结构体的时候可以在结构体的tag上增加json的tag,json tag的值可以有多个,中间以逗号隔开

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

如果第一个参数不是保留tag,那么这个参数将作为json序列化合反序列化时提取和输出的key

omitempty
-

第三方包

jsoniter
go get github.com/json-iterator/go
encoding/json
var json = jsoniter.ConfigCompatibleWithStandardLibrary
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)
}