[go]json序列化

// json字段别名
type User struct {
    Id      int    `json:"id,string"`
    Name    string `json:"username"`
    Age     int    `json:"age,omitempty"`
    Address string `json:"-"`
}

// 字段别名
    `json:"username"`      // 得到的字段key为自定义的别名
    `json:"id,string"`     // 将int float bool 等以string类型序列化展示. 
    `json:"age,omitempty"` // 如果是零值,则序列化时忽略这个字段,结果字段不存在
    `json:"-"`             // 绝对忽略这个字段
// 使用性能更好的github.com/json-iterator/go包序列化
// 只需要给json重新赋值


package main

import (
    "fmt"
    "github.com/json-iterator/go"
)

type User struct {
    Id      int    `json:"id,string"`
    Name    string `json:"username"`
    Age     int    `json:"age,omitempty"`
    Address string `json:"-"`
}

func main() {
    var json = jsoniter.ConfigCompatibleWithStandardLibrary
    u := User{
        Id:      12,
        Name:    "wendell",
        Age:     1,
        Address: "成都高新区",
    }
    data, err := json.Marshal(&u)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(data))
    //data:=[]byte(`{"id":"12","username":"wendell","age":1,"Address":"北京"}`)
    //u2 := &User{}
    //err = json.Unmarshal(data, u2)
    //if err != nil {
    //  fmt.Println(err)
    //}
    //fmt.Printf("%+v \n", u2)
}

猜你喜欢

转载自www.cnblogs.com/iiiiiher/p/11965898.html