Unmarshal()返回空结构 [英] Unmarshal() is returning empty structs

查看:46
本文介绍了Unmarshal()返回空结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件读取并将其加载到结构片中.我读入的行已正确加载,如块注释中所示.

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.

我遇到的问题是class变量不断返回空值.我在做什么错了?

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

*/

感谢您的帮助.我的问题是两部分,结构成员必须大写,而我却错过了json: "id"json: "name"

Thank you to isim 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"

推荐答案

您可以通过将字段的首字母更改为大写来导出Class结构中的字段,如下所示:

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

有关json包如何处理编码和解码的更多信息,可以在 json.Marshal json.Unmarshal 文档.

More information on how the json package handles encoding and decoding can be found in the json.Marshal and json.Unmarshal docs respectively.

这篇关于Unmarshal()返回空结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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