Dav*_*nes 0 tags json struct marshalling go
我正在尝试使用json.Marshal,但它拒绝接受我的struct标记。
我究竟做错了什么?
这是“ 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))
}
Run Code Online (Sandbox Code Playgroud)
我从“ 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
Run Code Online (Sandbox Code Playgroud)
我在运行程序时得到此输出。
% ./marshal
JSON = {"Name":"Alice","Age":29}
Run Code Online (Sandbox Code Playgroud)
请注意,字段名称与Go结构匹配,并且忽略json标签。
我想念什么?
哦,我的天啊!我只是想通了。json:和字段名称之间不允许有空格"name"。
“ go vet”错误消息("bad syntax")非常无用。
以下代码有效。你能看到区别么?
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))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2357 次 |
| 最近记录: |