Unmarshal() 返回空的结构体。

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

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&#39;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&#39;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(), &amp;class)
    
    		if err != nil {
    			fmt.Print(&quot;Error:&quot;, err)
    		} else {
    			a = append(a, class)
    		}
    	}
    	return a
    }
    
    type Class struct {
    	id   string
    	name string
    }
    
    /*
    Sample contents
    &quot;{&quot;id&quot;:124997,&quot;name&quot;:&quot;Environmental Sciences&quot;}
    {&quot;id&quot;:123905,&quot;name&quot;:&quot;Physical Education&quot;}
    {&quot;id&quot;:127834,&quot;name&quot;:&quot;Mandarin&quot;}
    {&quot;id&quot;:123507,&quot;name&quot;:&quot;Biology&quot;}
    {&quot;id&quot;:123883,&quot;name&quot;:&quot;German&quot;}
    {&quot;id&quot;:129148,&quot;name&quot;:&quot;German&quot;}
    {&quot;id&quot;:123545,&quot;name&quot;:&quot;Spanish&quot;}&quot;
    
    */
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: &quot;id&quot;` and `json: &quot;name&quot;`

</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.Marshaljson.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: &quot;id&quot;`
Name string `json: &quot;name&quot;`
}

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

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

发表评论

匿名网友

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

确定