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

时间:2016-07-09 18:27:24

标签: 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":""}

1 个答案:

答案 0 :(得分:2)

您正尝试使用%+v打印jsonObject, err := json.Marshal(DatabaseObject{}) if err != nil { log.Fatal(err) } fmt.Printf("%+v", jsonObject) 输出的表示。

json.Marshal返回一个字节切片,这正是您正在查看的内容。

fmt.Printf("%s", jsonObject)

将打印JSON字符串的字节。如果您使用fmt.Printf("%+v", string(jsonObject)),那么您将获得所需内容。

另一种选择是import re from binascii import unhexlify cp_escapes = re.compile(r"\'([0-9a-fA-F]{2})") def extract_cp_escapes(data): return unhexlify(''.join(marked_bytes.findall(data))) ,这样你就可以看到我在说什么我修改了你提供的游乐场。 https://play.golang.org/p/ipbSbryk1L