ufk
ufk

Reputation: 32094

cannot unmarshal array into Go struct when decoding array

I'm trying to properly decode JSON String to an object.

I defined the following structs:

type AjaxModelsList struct {
    Id float64 `json:"Id"`
    Name string `json:"Name"`
    CarId float64 `json:"CarId"`
    EngName string `json:"EngName"`
}

type AjaxModelsData struct {
    ModelList []AjaxModelsList `json:"ModelList"`
}

type AjaxModels struct {
    Status bool `json:"status"`
    Data map[string]AjaxModelsData `json:"data"`

}

the defined object is

{
 "status": true,
 "data": {
 "ModelList": [{
   "Id": 1,
   "Name": "foo",
   "CarId": 1,
   "EngName": "bar"
  }]
 }
}

and I unmarshall using the following code:

c :=AjaxModels{}
if err := json.Unmarshal(body_byte,&c); err != nil {
    log.Fatalf("an error occured: %v",err)
}

and I get the following output:

an error occured: json: cannot unmarshal array into Go struct field AjaxModels.data of type main.AjaxModelsData

since I used []AjaxModelsList it's a slice so I shouldn't be getting this error. I probably missed something, but what ?

Upvotes: 3

Views: 16432

Answers (1)

mkopriva
mkopriva

Reputation: 38203

In the json the data structure is object[key]array, while in Go Data is map[key]struct.slice. Change Data to be map[key]slice instead.

E.g.

type AjaxModels struct {
    Status bool                      `json:"status"`
    Data   map[string][]AjaxModelsList `json:"data"`
}

https://play.golang.org/p/Sh_vKVL-D--

Upvotes: 3

Related Questions