Golang结构体无法转换为JSON。

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

Golang Struct Won't Marshal to JSON

问题

我正在尝试将一个 Go 中的结构体转换为 JSON,但它无法转换,我无法理解原因。

我的结构体定义如下:

type PodsCondensed struct {
    pods []PodCondensed `json:"pods"`
}

func (p *PodsCondensed) AddPod(pod PodCondensed) {
    p.pods = append(p.pods, pod)
}

type PodCondensed struct {
    name   string   `json:"name"`
    colors []string `json:"colors"`
}

创建并转换一个测试结构体:

fake_pods := PodsCondensed{}

fake_pod := PodCondensed{
    name:   "tier2",
    colors: []string{"blue", "green"},
}

fake_pods.AddPod(fake_pod)
fmt.Println(fake_pods.pods)

jPods, _ := json.Marshal(fake_pods)
fmt.Println(string(jPods))

输出结果:

[{tier2 [blue green]}]
{}

我不确定问题出在哪里,我为所有的结构体导出了 JSON 数据,数据被正确地存储并可以打印出来。只是无法进行转换,这很奇怪,因为结构体中的所有内容都可以单独转换为 JSON。

英文:

I'm trying to marshal a struct in Go to JSON but it won't marshal and I can't understand why.

My struct definitions

type PodsCondensed struct {
    pods	[]PodCondensed	`json:"pods"`
}

func (p *PodsCondensed) AddPod(pod PodCondensed) {
    p.pods = append(p.pods, pod)
}

type PodCondensed struct {
    name	string		`json:"name"`
    colors	[]string	`json:"colors"`
}

Creating and marshaling a test struct

fake_pods := PodsCondensed{}

fake_pod := PodCondensed {
	name: "tier2",
	colors: []string{"blue", "green"},
}

fake_pods.AddPod(fake_pod)
fmt.Println(fake_pods.pods)

jPods, _ := json.Marshal(fake_pods)
fmt.Println(string(jPods))

Output

[{tier2 [blue green]}]
{}

I'm not sure what the issue is here, I export json data for all my structs, the data is being stored correctly and is available to print. It just wont marshal which is odd because everything contained in the struct can be marshaled to JSON on its own.

答案1

得分: 3

这是一个常见的错误:你没有在PodsCondensedPodCondensed结构体中导出值,所以json包无法使用它。使用大写字母来命名变量以解决这个问题:

type PodsCondensed struct {
    Pods    []PodCondensed  `json:"pods"`
}

type PodCondensed struct {
    Name    string      `json:"name"`
    Colors  []string    `json:"colors"`
}
  • 工作示例:http://play.golang.org/p/Lg3cTO7DVk
  • 文档:http://golang.org/pkg/encoding/json/#Marshal
英文:

This is a common mistake: you did not export values in the PodsCondensed and PodCondensed structures, so the json package was not able to use it. Use a capital letter in the variable name to do so:

type PodsCondensed struct {
    Pods    []PodCondensed  `json:"pods"`
}

type PodCondensed struct {
    Name    string      `json:"name"`
    Colors  []string    `json:"colors"`
}

huangapple
  • 本文由 发表于 2015年4月25日 04:27:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/29856890.html
匿名

发表评论

匿名网友

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

确定