douwei9759 2015-04-24 20:27
浏览 59
已采纳

Golang结构不会将其编组为JSON [重复]

This question already has an answer here:

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.

</div>
  • 写回答

1条回答 默认 最新

  • douzhantanju1849 2015-04-24 20:37
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败