Trying to unmarshal a string into json, but my struct definitions don't work. How can it be fixed?
package main
import "fmt"
import "encoding/json"
func main() {
x := `{
"Header": {
"Encoding-Type": [
"gzip"
],
"Bytes": [
"29"
]
}
}`
type HeaderStruct struct {
A string
B []string
}
type Foo struct {
Header HeaderStruct
}
var f Foo
if e := json.Unmarshal([]byte(x), &f); e != nil {
fmt.Println("Failed:", e)
} else {
fmt.Println("unmarshalled=", f)
}
}
The names of your variables don't match the names of the json keys and both of them are []string
. You can do
type HeaderStruct struct {
A []string `json:"Encoding-Type"`
B []string `json:"Bytes"
}
You need json annotations to tell the unmarshaller which data goes where, also the type of A
in your model is wrong, it should also be an array. I'm also going to change the names of your fields to something meaningful...
type HeaderStruct struct {
Encoding []string `json:"Encoding-Type"`
Bytes []string `json:"Bytes"
}