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 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟