簡體   English   中英

在golang中獲取json上的可空對象解組

[英]getting nullable object on json unmarshal in golang

轉到代碼(jsonTestParse.go)

(這只是我做的一個測試示例,請不要爭論我應該在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"}}

加上最好如何獲得這些價值?

那是因為您的cls結構體已經嵌入了學生 st私有結構體(小寫的未導出字段),更改為已導出字段應該起作用,即:

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

操場上看

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM