Creating JSON representation from Go struct

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

Creating JSON representation from Go struct

问题

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

package main

import "fmt"

func main() {
    type CommentResp struct {
        Id   string `json:"id"`
        Name string `json:"name"`
    }

    stringa := CommentResp{
        Id:   "42",
        Name: "Foo",
    }

    fmt.Println(stringa)
}

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

英文:

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

package main

import "fmt"

func main() {
	type CommentResp struct {
		Id   string `json: "id"`
		Name string `json: "name"`
	}

	stringa := CommentResp{
		Id:   "42",
		Name: "Foo",
	}

	fmt.Println(stringa)
}

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

答案1

得分: 9

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

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

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

type CommentResp struct {
    Id   string `json:"id"`
    Name string `json:"name"`
}

链接: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:

data, err := json.Marshal(stringa)
if err != nil {
     // Problem encoding stringa
     panic(err)
}
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:

type CommentResp struct {
    Id   string `json:"id"`
    Name string `json:"name"`
}

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:

确定