Golang中结构体JSON

参考

基本情况

// 定义结构体的时候,只有字段名是大写的,才会被编码到json当中
// 因此,json中并没有password字段
type Account struct {
    Email string
    password string
    Money float64
}

func main() {
    account := Account{
        Email: "[email protected]",
        password: "123456",
        Money: 100.5,
    }

    rs, err := json.Marshal(account)
    if err != nil{
        log.Fatalln(err)
    }

    fmt.Println(rs)
    fmt.Println(string(rs))
}

输出:

[123 34 69 109 97 105 108 34 58 34 114 115 106 50 49 55 64 103 109 97 105 108 46 99 111 109 34 44 34 77 111 110 101 121 34 58 49 48 48 46 53 125]
{"Email":"[email protected]","Money":100.5}

JSON字段重命名

type Account struct {
    Email    string  `json:"email"`
    Password string  `json:"pass_word"`
    Money    float64 `json:"money"`
}

func main() {
    account := Account{
        Email:    "[email protected]",
        Password: "123456",
        Money:    100.5,
    }

    rs, err := json.Marshal(account)
    ...
}

输出:

{"email":"[email protected]","pass_word":"123456","money":100.5}

更多功能

忽略字段-

type Account struct {
    Email    string  `json:"email"`
    Password string  `json:"password,omitempty"`
    Money    float64 `json:"-"`
}

输出

{"email":"[email protected]","money":100.5}

忽略空值字段omitempty

type Account struct {
    Email    string  `json:"email"`
    Password string  `json:"password,omitempty"`
    Money    float64 `json:"money"`
}
func main() {
    account := Account{
        Email:    "[email protected]",
        Password: "",
        Money:    100.5,
    }
    ...
}

输出

{"email":"[email protected]","money":100.5}

数值变为字符串string

type Account struct {
    Email    string  `json:"email"`
    Password string  `json:"password,omitempty"`
    Money    float64 `json:"money,string"`
}
func main() {
    account := Account{
        Email:    "[email protected]",
        Password: "123",
        Money:    100.50,
    }

    ...
}

输出

{"email":"[email protected]","money":"100.5"}
发布了290 篇原创文章 · 获赞 114 · 访问量 61万+

猜你喜欢

转载自blog.csdn.net/jason_cuijiahui/article/details/102738123