Go语言json数据的编码解码

 基础语法  2021-10-23  admin  913  1232

Go语言json数据的编码解码

package main

import (
	"encoding/json"
	"fmt"
)

type Product struct {
	Name      string  //`json:"name"`
	ProductID int64   `json:"product_id,string"`
	NoShow    string  `json:"-"` // 中划线- 表示不进行序列化
	Number    int     `json:"number,string"`
	Price     float64 `json:"price,string"`
	Price2    float64 `json:"price2,float64"`
	Price3    float64 `json:"price3,int"`
	IsOnSale  bool    `json:"is_on_sale,string"`
	IsShow    bool    `json:"is_show,bool"`
	Empty     string  `json:"empty,omitempty"` //omitempty,tag里面加上omitempy,可以在序列化的时候忽略0值或者空值
}

func main() {
	product := Product{
		Name:      "华为手机",
		ProductID: 1001,
		NoShow:    "中划线- 表示不进行序列化",
		Number:    200,
		Price:     1999.99,
		Price2:    1899.11,
		Price3:    1599.99,
		IsOnSale:  false,
		IsShow:    false,
		Empty:     "",
	}

	//json编码
	jsonEncode, _ := json.Marshal(product)

	fmt.Println(string(jsonEncode)) //{"Name":"华为手机","product_id":"1001","number":"200","price":"1999.99","price2":1899.11,"price3":1599.99,"is_on_sale":"false","is_show":false}



	//json解码
	var strData = `{"Name":"华为手机","product_id":"1001","NoShow":"中划线- 表示不进行序列化","number":"200","price":"1999.99","price2":1899.11,"price3":1599.99,"is_on_sale":"false","is_show":false,"empty":""}`
	jsonDecode := &Product{}
	err := json.Unmarshal([]byte(strData), jsonDecode)

	fmt.Println(err)      //<nil>
	fmt.Println(jsonDecode)        //&{华为手机 1001  200 1999.99 1899.11 1599.99 false false }
	fmt.Println(*jsonDecode)       //{华为手机 1001  200 1999.99 1899.11 1599.99 false false }
	fmt.Printf("%+v", *jsonDecode) //{Name:华为手机 ProductID:1001 NoShow: Number:200 Price:1999.99 Price2:1899.11 Price3:1599.99 IsOnSale:false IsShow:false Empty:}
}


//格式 Tag标签  `json:"字段名,omitempty,-,type类型"`

//Tag,tag就是标签,给结构体的每个字段打上一个标签,标签冒号前是类型,后面是标签名。

//omitempty,tag里面加上omitempy,可以在序列化的时候忽略0值或者空值

//-,中划线- 表示不进行序列化

//type,有些时候在序列化或者反序列化的时候,可能结构体类型和需要的类型不一致,这个时候可以指定,支持string,number和boolean


如果文章对您有帮助,点击下方的广告,支持一下作者吧!

转载必须注明出处:

Go语言json数据的编码解码 —— code.cent123.com

相关推荐


linux 系统最简单的安装 go 开发环境步骤

1. 官网下载放在 /godev 目录https://golang.google.cn/dl/或wget https://dl.google.com/go/go1.22.2.linux-amd64.tar.gz或curl -O https://dl.google.com/go/go1.22.2.linux-386.tar.gz2. 解压tar -xvf go1.22.2.linux-amd64.t

go 生成密码 php的 password_hash go实现

packagemain import( &quot;fmt&quot; &quot;golang.org/x/crypto/bcrypt&quot; ) funcmain(){ hashedPassword:=passwordHash(&quot;123456&quot;) fmt.Println(hashedPassword) hashedPassword=

使用 govcl 开发桌面UI 在 Lazarus IDE 编译中报错

使用 govcl 开发桌面UI 在 Lazarus IDE 编译中报错go build -i -buildmode=exe -ldflags=&quot;-H windowsgui&quot; -tags=&quot;tempdll&quot; -o &quot;project1.exe&quot;flag provided but not defined: -iusage: go build [

go 实现php的 password_hash() 密码加密方法

go 实现php的 password_hash() 密码加密方法