Go : When will json.Unmarshal to struct return error?

后端 未结 3 1428
时光说笑
时光说笑 2020-12-31 04:15

Assume i have a struct like

type A struct{
  name string`json:\"name\"`
}

Then in main i have code

var jsonString string =          


        
3条回答
  •  别那么骄傲
    2020-12-31 04:32

    To add to icza's answer, you can also get an error if you try to Unmarshal into a typed nil pointer. This can happen if, for example, you make a slice of pointers to a particular type, then try and unmarshal into a particular one of those pointers.

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type Example struct {Name string}
    
    
    func main() {
            exs := make([]*Example, 5)
            err := json.Unmarshal([]byte(`{"name":"jane"}`), exs[0])
            fmt.Println(err)
    }
    // json: Unmarshal(nil *main.Example)
    

提交回复
热议问题