Golang-Json標準包

  1. Json Tag的妙用(-、omitempty、string、number)
package golang

import (
    "encoding/json"
    "fmt"
    "log"
    "testing"
)

type Product struct {
    Name      string  `json:"name"`
    Desc      string  `json:"desc,omitempty"` //omitempty 如果空就不輸出
    ProductID int64   `json:"product_id"`
    GoodsID   int64   `json:"goods_id"`
    Price     float64 `json:"price,string"` //string 以string類型輸出、讀入

    //Additional
    Additional string `json:"-"` //- 不輸出字段
}

func Test_Marshal(t *testing.T) {
    var prduct = &Product{
        Name:      "音響",
        Desc:      "",
        ProductID: 103131441,
        GoodsID:   210313140,
        Price:     99.99,

        Additional: "不輸出Json段",
    }

    str, err := json.Marshal(prduct)
    if err != nil {
        log.Fatalf("Marshal Err[%v]", err)
        return
    }

    fmt.Println(string(str))
    //Output:
    //{"name":"音響","product_id":103131441,"goods_id":210313140,"price":"99.99"}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章