Reputation: 391
I want to unmarshal the following JSON into a struct:
{"MAIN":{"data":[{"KEY1":"1111111","KEY2":"2222222","KEY3":0,"KEY4":"AAAAAAA","KEY5":"9999","KEY6":"4","KEY7":"BBBBBBB"}]}}
I have tried to modify the jsonStruct
in various ways, but the struct is always empty:
package main
import (
"encoding/json"
"fmt"
)
type jsonStruct struct {
main struct {
data []struct {
Key1 string `json:"KEY1"`
Key2 string `json:"KEY2"`
Key3 int `json:"KEY3"`
Key4 string `json:"KEY4"`
Key5 string `json:"KEY5"`
Key6 string `json:"KEY6"`
Key7 string `json:"KEY7"`
} `json:"data"`
} `json:"MAIN"`
}
func main() {
jsonData := []byte(`{"MAIN":{"data":[{"KEY1":"1111111","KEY2":"2222222","KEY3":0,"KEY4":"AAAAAAA","KEY5":"9999","KEY6":"4","KEY7":"BBBBBBB"}]}}`)
var js jsonStruct
err := json.Unmarshal(jsonData, &js)
if err != nil {
panic(err)
}
fmt.Println(js)
}
Output:
{{[]}}
The JSON I have worked with in the past contained no brackets, so I suspect that the problem is related to them.
Can anyone help?
https://play.golang.org/p/pymKbOqcM-
Upvotes: 2
Views: 1188
Reputation: 13681
This is happening because other packages (encoding/json
) can't access private fields (even with reflection). In go, private fields are fields starting with a lower case character. To fix this, make your struct contains public fields (which start with an upper case letter):
type jsonStruct struct {
Main struct {
Data []struct {
Key1 string `json:"KEY1"`
Key2 string `json:"KEY2"`
Key3 int `json:"KEY3"`
Key4 string `json:"KEY4"`
Key5 string `json:"KEY5"`
Key6 string `json:"KEY6"`
Key7 string `json:"KEY7"`
} `json:"data"`
} `json:"MAIN"`
}
https://play.golang.org/p/lStXAvDtpZ
Upvotes: 8