为什么struct字段显示为空?

use*_*109 3 json struct go

我正在努力从以下代码中获取正确的输出:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    var jsonBlob3 = []byte(`[
        {"name": "Platypus", "spec": "Monotremata", "id":25 },
        {"name": "Quoll",    "spec": "Dasyuromorphia", "id":25 }
    ]`)
    type Animal2 struct {
        name  string
        spec string
        id uint32
    }
    var animals []Animal2
    err := json.Unmarshal(jsonBlob3, &animals)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Printf("%+v\n", animals)
}
Run Code Online (Sandbox Code Playgroud)

游乐场片段

打印时结构字段为空.我确信在某个地方有一个愚蠢的错误,但我仍然是Go的新手,我已经被困在这几个小时了.请帮忙.

icz*_*cza 6

这已经出现了很多次.问题是只有导出的字段可以编组/解组.

通过以大写(大写)字母开始输出结构字段.

type Animal2 struct {
    Name  string
    Spec string
    Id uint32
}
Run Code Online (Sandbox Code Playgroud)

Go Playground尝试一下.

请注意,JSON文本包含带有小写文本的字段名称,但该json包"足够聪明"以匹配它们.如果它们完全不同,您可以使用struct标签告诉json包在JSON文本中如何找到它们(或它们应该如何编组),例如:

type Animal2 struct {
    Name  string `json:"json_name"`
    Spec string  `json:"specification"`
    Id uint32    `json:"some_custom_id"`
}
Run Code Online (Sandbox Code Playgroud)