golang json判断类型

json怎么判断类型

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

看上去很粗暴但是很实用,并没有查到满意的方法,待补充。

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

//type Product struct {
//	Name      string
//	ProductID int64
//	Number    int
//	Price     float64
//	IsOnSale  bool
//}
// Product _
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"`
}

var test struct {
	t interface{}
}

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

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

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/105542220