How to decode json into structs

后端 未结 3 1213
既然无缘
既然无缘 2021-02-08 00:21

I\'m trying to decode some json in Go but some fields don\'t get decoded. See the code running in browser here:

What am I doing wrong?

I need only the MX reco

3条回答
  •  滥情空心
    2021-02-08 01:26

    As per the go documentaiton about json.Unmarshal, you can only decode toward exported fields, the main reason being that external packages (such as encoding/json) cannot acces unexported fields.

    If your json doesn't follow the go convention for names, you can use the json tag in your fields to change the matching between json key and struct field.

    Exemple:

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type T struct {
        Foo string `json:"foo"`
    }
    
    func main() {
        text := []byte(`{"foo":"bar"}`)
        var t T
        err := json.Unmarshal(text, &t)
        if err != nil {
            panic(err)
        }
        fmt.Println(t)
    }
    

提交回复
热议问题