dongmo2324 2016-07-09 18:27
浏览 60
已采纳

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

So i want to marshal data to JSON. The basic struct looks like this:

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"`
}

Here is the (working) Playground version: https://play.golang.org/p/GI3nAo7L4a

When i use this code in my program however, the result is very different. Here is my code:

jsonObject, err := json.Marshal(DatabaseObject{})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("%+v", jsonObject)

It prints:

[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]

Does anyone know why json.Marshal does not work here? It's an empty struct, it should look like this

{"preferences":null,"texts":null,"options":null,"gender":"","email":""}
  • 写回答

1条回答 默认 最新

  • dongyi7669 2016-07-09 19:20
    关注

    You're trying to print the representation of what json.Marshal outputs with %+v.

    json.Marshal returns a byte slice which is exactly what you're looking at.

    jsonObject, err := json.Marshal(DatabaseObject{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%+v", jsonObject)
    

    Will print the bytes for the JSON string. If instead you use fmt.Printf("%s", jsonObject) you'll get what you're looking for.

    Another option would be fmt.Printf("%+v", string(jsonObject)) just so you can see what I'm talking about I've modified the playground you provided. https://play.golang.org/p/ipbSbryk1L

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题