2016-12-06 50 views
0

Go代碼(jsonTestParse.go)越來越爲空的對象JSON解組在golang

(這僅僅是一個測試例子我做了,請不要認爲我應該在學生CLS結構的 使用列表)

package main 

import (
    "encoding/json" 
    "fmt" 
    "io/ioutil" 
    "os" 
) 

type student struct { 
    ID  string `json:"id"` 
    Name  string `json:"name"` 
    Standard string `json:"std"` 
} 

type cls struct { 
    st student `json:"cls"` 
} 

func getValues() (cls, error) { 
    var clss cls 
    dataBytes, err := ioutil.ReadFile("studentclass.json") 
    if err != nil { 
     fmt.Printf("File error: %v\n", err) 
     os.Exit(1) 
    } 
    err = json.Unmarshal(dataBytes, &clss) 
    if err != nil { 
     fmt.Errorf("%s", err) 
    } 
    return clss, err 
} 

func main() { 
    s, err := getValues() 
    fmt.Printf("%#v\n", s) 
    fmt.Println(err) 
} 

JSON文件(studentclass.json)

{ 
    "cls": { 
     "id": "1", 
     "name": "test", 
     "std": "0" 
    } 
} 

當我與go run jsonTestParse.go運行這段代碼是給了我這樣的輸出:

main.cls{st:main.student{ID:"", Name:"", Standard:""}} 
<nil> 

請幫我,爲什麼我得到這個空對象

main.cls{st:main.student{ID:"", Name:"", Standard:""}} 

,而不是這個

main.cls{st:main.student{ID:"1", Name:"test", Standard:"0"}} 

另外這將是很好的幫助如何獲得這些值?

回答

3

那是因爲你CLS結構嵌入了專用結構學生(小寫不導出字段)st,改變出口領域應該工作,即:

type cls struct { 
    // St field will be unmarshalled 
    St student `json:"cls"` 
} 

playground

+0

哇!謝謝!我可以找到關於此的文件嗎?這對我很有幫助! – rsudip90

+0

@ rsudip90,很高興它有幫助,你可以從Go API文檔[這裏](https://golang.org/pkg/encoding/json/#Unmarshal)讀取它,特別是這一行:'Unmarshal將只設置導出的字段的結構 – Anzel