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



此问题已经存在 在这里有答案:</ p>





  • 我的结构未编组为json [重复]



    3个答案
    < / span>

    </ li>

    </ ul>

    </ div>

    我正在尝试在Go to JSON中封送一个结构,但它不会 元帅,我不明白为什么。 </ p>

    我的结构定义</ p>

     类型PodsCondensed结构{
    pods] PodCondensedjson:“ pods”
    }

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

    type PodCondensed结构{
    name stringjson:“ name”
    colors [] stringjson:“ colors”
    }
    </ code> </ pre>

    创建并封送测试结构</ p>

      fake_pods:= PodsCondensed {} 
    
    

    fake_pod:= PodCondensed {
    名称:“ tier2”,
    颜色:[] string {“ blue”,“ green”},
    }

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

    jPods,_:= json.Marshal(fake_pods)
    fmt.Println(string(jPods))
    </ code> </ pre>

    < p> Output </ p>

      [{tier2 [blue green]}] 
    {}
    </ code> </ pre>

    我是 不确定问题出在哪里,我为我所有的结构导出json数据,该数据已正确存储并可以打印。 只是不会编组,这很奇怪,因为该结构中包含的所有内容都可以单独编组为JSON。</ p>
    </ div>

展开原文

原文

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个回答



这是一个常见错误:您没有在 PodsCondensed </ code>和 PodCondensed </ export>中导出值 code>结构,因此json包无法使用它。 请在变量名中使用大写字母:</ p>

  type PodsCondensed struct {
Pods [] PodCondensedjson:“ pods”
}

type PodCondensed struct {
名称字符串json:“ name”
颜色[]字符串json:“ colors”
}
</ code> </ pre>

展开原文

原文

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"`
}

dqkx69935
dqkx69935 知道了,谢谢。 抱歉,意外重复,我不知道这个问题有多普遍。
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐