英文:
Unmarshal() is returning empty structs
问题
我正在尝试从文件中读取内容并将其加载到一个结构体切片中。根据块注释中显示的内容,我成功加载了读取的行。
我遇到的问题是class
变量始终返回空值。我做错了什么?
func loadClasses(path string) []Class {
var a []Class
inFile, _ := os.Open(path)
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
scanner.Split(bufio.ScanLines)
var class Class
for scanner.Scan() {
var err = json.Unmarshal(scanner.Bytes(), &class)
if err != nil {
fmt.Print("Error:", err)
} else {
a = append(a, class)
}
}
return a
}
type Class struct {
Id string `json:"id"`
Name string `json:"name"`
}
/*
Sample contents
"{\"id\":124997,\"name\":\"Environmental Sciences\"}
{\"id\":123905,\"name\":\"Physical Education\"}
{\"id\":127834,\"name\":\"Mandarin\"}
{\"id\":123507,\"name\":\"Biology\"}
{\"id\":123883,\"name\":\"German\"}
{\"id\":129148,\"name\":\"German\"}
{\"id\":123545,\"name\":\"Spanish\"}"
*/
感谢ivan.sim的帮助。我的问题有两个部分,结构体成员必须大写,并且我漏掉了`json:"id"`和`json:"name"`。
<details>
<summary>英文:</summary>
I'm trying to read from a file and load it into a struct slice. The lines that I read in are loaded correct as shown in the block comment.
The issue I'm having is that the `class` variable keeps coming back with empty values. What am I doing wrong?
func loadClasses(path string) []Class {
var a []Class
inFile, _ := os.Open(path)
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
scanner.Split(bufio.ScanLines)
var class Class
for scanner.Scan() {
var err = json.Unmarshal(scanner.Bytes(), &class)
if err != nil {
fmt.Print("Error:", err)
} else {
a = append(a, class)
}
}
return a
}
type Class struct {
id string
name string
}
/*
Sample contents
"{"id":124997,"name":"Environmental Sciences"}
{"id":123905,"name":"Physical Education"}
{"id":127834,"name":"Mandarin"}
{"id":123507,"name":"Biology"}
{"id":123883,"name":"German"}
{"id":129148,"name":"German"}
{"id":123545,"name":"Spanish"}"
*/
Thank you to ivan.sim for the help. My issue was two part, the struct members had to be capitalized and I was missing the `json: "id"` and `json: "name"`
</details>
# 答案1
**得分**: 7
你可以通过将`Class`结构体中的字段的首字母改为大写来导出这些字段,如下所示:
```go
type Class struct{
Id string
Name string
}
此外,你还可以像下面这样为字段添加标签:
type Class struct{
Id string `json:"id"`
Name string `json:"name"`
}
关于json
包如何处理编码和解码的更多信息可以在json.Marshal
和json.Unmarshal
文档中找到。
英文:
You can export the fields in your Class
struct by changing the first letter of the fields to upper case like this:
type Class struct{
Id string
Name string
}
Optionally, you can also add tags to the fields like this:
type Class struct{
Id string `json: "id"`
Name string `json: "name"`
}
More information on how the json
package handles encoding and decoding can be found in the json.Marshal
and json.Unmarshal
docs respectively.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论