go json序列化输出byte数组错误,输出无意义字符

使用json对一个struct类型变量序列化,输出的byte数组没有意义

type cat struct {
    
    
	id   int    `json:"id,omitempty"`
	name string `json:"name,omitempty"`
}

func main() {
    
    
	c := &cat{
    
    
		id:   1001,
		name: "HelloKitty",
	}
	b, _ := json.Marshal(c)
	str := string(b)
	fmt.Println(c, b, str)
}

输出如下

&{
    
    1001 HelloKitty} [123 135] {
    
    }

原因是struct的字段必须是export状态,也就是首字母大写

修改如下后输出正常

type cat struct {
    
    
	Id   int    `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
}

func main() {
    
    
	c := &cat{
    
    
		Id:   1001,
		Name: "HelloKitty",
	}
	b, _ := json.Marshal(c)
	str := string(b)
	fmt.Println(c, b, str)
}
&{
    
    1001 HelloKitty} [123 34 105 100 34 58 49 48 48 49 44 34 110 97 109 101 34 58 34 72 101 108 108 111 75 105 116 116 121 34 125] {
    
    "id":1001,"name":"HelloKitty"}

猜你喜欢

转载自blog.csdn.net/weixin_45271005/article/details/131692236