所以我想将数据编码为 JSON。基本结构如下所示:
type DatabaseObject struct {
Preferences []int `json:"preferences"`
Texts map[string]string `json:"texts"`
Options map[string]string `json:"options"`
Gender string `json:"gender"`
EMail string `json:"email"`
}
这是(工作中的) Playground 版本:https://play.golang.org/p/GI3nAo7L4a
然而,当我在我的程序中使用这段代码时,结果却大不相同。这是我的代码:
jsonObject, err := json.Marshal(DatabaseObject{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", jsonObject)
它打印:
[123 34 112 114 101 102 101 114 101 110 99 101 115 34 58 110 117 108 108 44 34 116 101 120 116 115 34 58 110 117 108 108 44 34 111 112 116 105 111 110 115 34 58 110 117 108 108 44 34 103 101 110 100 101 114 34 58 34 34 44 34 101 109 97 105 108 34 58 34 34 125]
有谁知道为什么 json.Marshal 在这里不起作用?这是一个空结构,应该是这样的
{"preferences":null,"texts":null,"options":null,"gender":"","email":""}
最佳答案
您正在尝试使用 %+v
打印 json.Marshal
输出的表示。
json.Marshal返回一个字节 slice ,这正是您正在查看的内容。
jsonObject, err := json.Marshal(DatabaseObject{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", jsonObject)
将打印 JSON 字符串的字节。相反,如果您使用 fmt.Printf("%s", jsonObject)
,您将获得所需的内容。
另一个选项是 fmt.Printf("%+v", string(jsonObject))
这样您就可以明白我在说什么 我已经修改了您提供的 Playground 。 https://play.golang.org/p/ipbSbryk1L
关于json.Marshal 对两个对象的行为不同 (Go/Golang),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38284984/