首页 > 其他分享 >go json.Marshal 和 json.Unmarshal与结构体

go json.Marshal 和 json.Unmarshal与结构体

时间:2022-10-17 11:12:13浏览次数:72  
标签:err string weight fmt json go Unmarshal Marshal

结构体属性名字小写会被忽略

package main

import (
    "encoding/json"
    "fmt"
)

type People struct {
    name   string `json:"name"`
    Height string `json:"height"`
}
type Student struct {
    Age    string `json:"age"`
    weight string `json:"weight"`
}

func main() {
    s := Student{
        Age:    "13",
        weight: "33", //属性小写,在使用Marshal转换成切片的时候会被忽略
    }
    if sslice, err := json.Marshal(s); err == nil {
        fmt.Println(string(sslice)) // {"age":"13"} 忽略了小写的weight属性
    }

    js := `{
    "name":"11",
    "Height":"179"
}`
    var p People
    err := json.Unmarshal([]byte(js), &p)
    if err != nil {
        fmt.Println("err :", err)
        return
    }
    fmt.Println("people:", p) //people: { 179}   忽略了小写name 属性

}

 

标签:err,string,weight,fmt,json,go,Unmarshal,Marshal
From: https://www.cnblogs.com/zxqblogrecord/p/16798485.html

相关文章