为什么结构字段显示为空? [英] Why struct fields are showing empty?

查看:37
本文介绍了为什么结构字段显示为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am struggling to get the correct output from the following code:

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
", animals)
}

游乐场片段

打印时结构字段为空.我确信某处有一个愚蠢的错误,但我对 Go 还是个新手,而且我已经坚持了几个小时.请帮忙.

The struct fields are empty when printed. I am sure there is a dumb mistake somewhere but I am still new to Go and I have been stuck at this for hours. Please help.

推荐答案

这个问题已经出现很多次了.问题是只能对导出的字段进行编组/解组.

This has come up so many times. The problem is that only exported fields can be marshaled/unmarshaled.

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

Export the struct fields by starting them with capital (upper-case) letters.

type Animal2 struct {
    Name string
    Spec string
    Id   uint32
}

Go Playground 上试试.

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

Note that the JSON text contains the field names with lowercased text, but the json package is "clever" enough to match them. If they would be completely different, you could use struct tags to tell the json package how they are found (or how they should be marshaled) in the JSON text, e.g.:

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

这篇关于为什么结构字段显示为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆