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"}}
另外這將是很好的幫助如何獲得這些值?
哇!謝謝!我可以找到關於此的文件嗎?這對我很有幫助! – rsudip90
@ rsudip90,很高興它有幫助,你可以從Go API文檔[這裏](https://golang.org/pkg/encoding/json/#Unmarshal)讀取它,特別是這一行:'Unmarshal將只設置導出的字段的結構 – Anzel