golang json例子

Example1

package main
import (
	"encoding/json"
	"fmt"
)

type Product struct {
	Name      string
	ProductID int64
	Number    int
	Price     float64
	IsOnSale  bool
}

func main() {
	p := &Product{}

	p.Name = "Hodge"
	p.IsOnSale = true
	p.Number = 1
	p.Price = 2.00
	p.ProductID = 3
	fmt.Println(p) // &{Hodge 3 1 2 true}
	fmt.Println(p.Name) // Hodge
	data, _ := json.Marshal(p)

	fmt.Println(string(data)) // {"Name":"Hodge","ProductID":3,"Number":1,"Price":2,"IsOnSale":true}
}

Example2(Tag)

给变量加了标签

type Product struct {
	Name      string  `json:"name"`
	ProductID int64   `json:"-"` // 表示不进行序列化
	Number    int     `json:"number"`
	Price     float64 `json:"price"`
	IsOnSale  bool    `json:"_is_on_sale"`
}

输出结果对比

{"name":"Hodge","number":1,"price":2,"_is_on_sale":"true"}
{"Name":"Hodge","ProductID":3,"Number":1,"Price":2,"IsOnSale":true}

Example3

omitempty如果值为0则不输出

type Product struct {
	Name      string  `json:"name"`
	ProductID int64   `json:"-"` // 表示不进行序列化
	Number    int     `json:"number, omitempty"` // 错误,逗号后有空格会使json失效
	Price     float64 `json:"price,omitempty"`
	IsOnSale  bool    `json:"_is_on_sale"`
}

func main() {
	p := &Product{}

	p.Name = "Hodge"
	p.IsOnSale = false
	p.Number = 0
	p.Price = 0.00
	p.ProductID = 3
	fmt.Println(p) // &{Hodge 3 0 0 false}
	fmt.Println(p.Name) // Hodge
	data, _ := json.Marshal(p)

	fmt.Println(string(data))// {"name":"Hodge","number":0,"_is_on_sale":"false"}
}

Example4(反序列化的类型转换)

package main
import (
	"encoding/json"
	"fmt"
)

type Product struct {
	Name      string  `json:"name"`
	ProductID int64   `json:"-"` // 表示不进行序列化
	Number    int     `json:"number, string"`
	Price     float64 `json:"price, int"`
	IsOnSale  bool    `json:"_is_on_sale"`
}
 
func main() {
	p := &Product{}

	p.Name = "Hodge"
	p.IsOnSale = false
	p.Number = 0
	p.Price = 0.00
	p.ProductID = 3
	data, _ := json.Marshal(p)

	fmt.Println(string(data))// {"Name":"Hodge","ProductID":3,"Number":1,"Price":2,"IsOnSale":true}


	//t := test{}
	q := &Product{}
	json.Unmarshal([]byte(data), q)
	fmt.Println(*q)

	if q.Number == '0' {
		fmt.Println("q.Number is string!Pass" )
	}
	if q.Number == 0 {
		fmt.Println("q.Number is not string!Wrong" )
	}
}

https://www.cnblogs.com/yangshiyu/p/7045954.html

发布了399 篇原创文章 · 获赞 266 · 访问量 41万+

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/105541229
今日推荐