I have this JSON data:
{
"InfoA" : [256,256,20000],
"InfoB" : [256,512,15000],
"InfoC" : [208,512,20000],
"DEFAULT" : [256,256,20000]
}
With JSON-to-Go, I get this Go type definition:
type AutoGenerated struct {
InfoA []int `json:"InfoA"`
InfoB []int `json:"InfoB"`
InfoC []int `json:"InfoC"`
DEFAULT []int `json:"DEFAULT"`
}
With this code (play.golang.org)
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
)
func main() {
type paramsInfo struct {
InfoA []int `json:"InfoA"`
InfoB []int `json:"InfoB"`
InfoC []int `json:"InfoC"`
DEFAULT []int `json:"DEFAULT"`
}
rawJSON := []byte(`{
"InfoA" : [256,256,20000],
"InfoB" : [256,512,15000],
"InfoC" : [208,512,20000],
"DEFAULT" : [256,256,20000]
}`)
var params []paramsInfo
err := json.Unmarshal(rawJSON, ¶ms)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
}
I get error json: cannot unmarshal object into Go value of type []main.paramsInfo
I don't understand why. Can you help me?
The JSON source is a single object, yet you try to unmarshal it into a slice. Change the type of params
to paramsInfo
(non-slice):
var params paramsInfo
err := json.Unmarshal(rawJSON, ¶ms)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Printf("%+v", params)
And with that the output (try it on the Go Playground):
{InfoA:[256 256 20000] InfoB:[256 512 15000] InfoC:[208 512 20000]
DEFAULT:[256 256 20000]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With