json.Marshal 对两个对象的行为不同 (Go/Golang)

标签 json go struct marshalling

所以我想将数据编码为 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/

相关文章:

mysql - 我可以将 Laravel JSONWhere 子句与 MariaDB 10.2.16 LongText 列一起使用吗?

c - 如何从 Golang 访问 C 指针数组

使用位域比较 C 中的结构

c - 将结构传递给函数的正确方法是什么?

java - 在 JAVA 中使用 GSON 序列化内部类

java - 将来自 Web 服务的大型 JSON 数据插入 mongodb

mongodb - 在 mongodb 记录中使用 time.Time

c - 将数据添加到函数内部的结构中,但外部的值为空

android - 对等通信选项

go - 如何使用 Golang 获取发布的二进制数据的文件名?