我正在尝试使用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标记。
我遗漏了什么?
发布于 2018-10-30 03:00:35
我的天哪!我刚想通了。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))
}
https://stackoverflow.com/questions/53051979
复制相似问题