Creating JSON representation from Go struct

huangapple go评论113阅读模式
英文:

Creating JSON representation from Go struct

问题

我正在尝试从一个结构体创建一个JSON字符串:

  1. package main
  2. import "fmt"
  3. func main() {
  4. type CommentResp struct {
  5. Id string `json:"id"`
  6. Name string `json:"name"`
  7. }
  8. stringa := CommentResp{
  9. Id: "42",
  10. Name: "Foo",
  11. }
  12. fmt.Println(stringa)
  13. }

这段代码输出的是{42 foo},但我期望输出的是{"Id":"42","Name":"Foo"}

英文:

I am trying to create a JSON string from a struct:

  1. package main
  2. import "fmt"
  3. func main() {
  4. type CommentResp struct {
  5. Id string `json: "id"`
  6. Name string `json: "name"`
  7. }
  8. stringa := CommentResp{
  9. Id: "42",
  10. Name: "Foo",
  11. }
  12. fmt.Println(stringa)
  13. }

This code prints {42 foo}, but I expected {"Id":"42","Name":"Foo"}.

答案1

得分: 9

你正在打印的是fmtCommentResp结构体进行序列化的结果。相反,你应该使用json.Marshal来获取编码后的JSON表示:

  1. data, err := json.Marshal(stringa)
  2. if err != nil {
  3. // 编码stringa时出现问题
  4. panic(err)
  5. }
  6. fmt.Println(string(data))

此外,你的json结构标签是无效的;在冒号:和引号之间不能有空格:

  1. type CommentResp struct {
  2. Id string `json:"id"`
  3. Name string `json:"name"`
  4. }

链接:https://play.golang.org/p/ogWKQ3M6tb

链接:https://play.golang.org/p/eQiyTk6-vQ

英文:

What you are printing is fmt's serialization of the CommentResp struct. Instead, you want to do is use json.Marshal to get the encoded JSON repsentation:

  1. data, err := json.Marshal(stringa)
  2. if err != nil {
  3. // Problem encoding stringa
  4. panic(err)
  5. }
  6. fmt.Println(string(data))

https://play.golang.org/p/ogWKQ3M6tb

Also, your json struct tags are not valid; there cannot be a space between : and the quoted string:

  1. type CommentResp struct {
  2. Id string `json:"id"`
  3. Name string `json:"name"`
  4. }

https://play.golang.org/p/eQiyTk6-vQ

huangapple
  • 本文由 发表于 2016年12月11日 21:26:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/41086654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定