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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章