为什么结构字段显示为空?

huangapple go评论86阅读模式
英文:

Why struct fields are showing empty?

问题

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

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

当打印时,结构体字段为空。我确定有一个愚蠢的错误,但我对Go还很陌生,我已经卡在这里几个小时了。请帮忙。

英文:

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

Playground snippet

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.

答案1

得分: 11

这个问题已经出现了很多次。问题在于只有导出的字段才能进行编组/解组。

通过将结构体字段以大写字母开头来导出它们。

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"`
}
英文:

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
}

Try it on the Go Playground.

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

huangapple
  • 本文由 发表于 2015年9月20日 09:40:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/32674913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定