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)
}

原文地址:https://www.cnblogs.com/ivy-blogs/p/13359574.html