【问题标题】:Why struct fields are showing empty?为什么结构字段显示为空?
【发布时间】:2015-12-16 22:54:24
【问题描述】:

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

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)
}

游乐场snippet

打印时结构字段为空。我确信某处有一个愚蠢的错误,但我还是 Go 新手,我已经被困了好几个小时了。请帮忙。

【问题讨论】:

标签: json go struct


【解决方案1】:

这已经出现过很多次了。问题是只有导出的字段可以被封送/解封。

以大写(大写)字母开头来导出结构字段。

type Animal2 struct {
    Name string
    Spec string
    Id   uint32
}

Go Playground 上试用。

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

type Animal2 struct {
    Name string `json:"json_name"`
    Spec string `json:"specification"`
    Id   uint32 `json:"some_custom_id"`
}

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 2016-01-02
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多