gpt4 book ai didi

json - 为什么 Go json.Marshal 拒绝这些结构标签? json 标签的正确语法是什么?

转载 作者:IT王子 更新时间:2023-10-29 02:26:09 34 4
gpt4 key购买 nike

<分区>

我正在尝试使用 json.Marshal,但它拒绝接受我的结构标签。

我做错了什么?

这是“marshal.go”的源代码

https://play.golang.org/p/eFe03_89Ly9

package main

import (
"encoding/json"
"fmt"
)

type Person struct {
Name string `json: "name"`
Age int `json: "age"`
}

func main() {
p := Person{Name: "Alice", Age: 29}
bytes, _ := json.Marshal(p)
fmt.Println("JSON = ", string(bytes))
}

我从“go vet marshal.go”得到这些错误信息

./marshal.go:9: struct field tag `json: "name"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value
./marshal.go:10: struct field tag `json: "age"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value

我在运行程序时得到了这个输出。

% ./marshal
JSON = {"Name":"Alice","Age":29}

注意字段名称匹配 Go 结构并忽略 json 标签。

我错过了什么?

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com