type Layout struct {
LayoutID int `json:"layoutID"`
Data []Widget `json:"data"`
}
type Widget struct {
WidgetID int `json:"widgetID"`
Name string `json:"name"`
Type string `json:"type"`
Data []interface{} `json:"data"`
}
type Product struct {
ProductID int `json:"productID"`
Name string `json:"name"`
}
type Voucher struct {
VoucherID int `json:"voucherID"`
Name string `json:"name"`
}
@bklimczak Thanks a lot for helping me, It’s really helped me. But, I’ve another problem after unmarshall, I’ve found data on Widget struct is a []interface{} type.
I’ve tried to cast these codes, but the result is error invalid type assertion. How can I do or any other way to cast into Product and Voucher Struct?
In the loop you wrote, the Data is type widget. You don’t have to cast it. What you want to do is iterate over the Data in it https://play.golang.org/p/QoLQxyv1zKr
I see that, but Data on widget 1 is product struct such as I set ProductID, Name and Data on widget 2, not Product but also is Voucher struct, so why I cast it because on Data the other is not the same. So that why I set like this https://play.golang.org/p/2zmGTlbC9pB.
And I’ve found it, after unmarshall layout the result on widget 2 data have ProductID=0, not VoucherID=1.
type Widget struct {
WidgetID int `json:"widgetID"`
Name string `json:"name"`
Type string `json:"type"`
Data []interface{} `json:"data"`
}
Because Data on Widget is dynamic, so that I set type []interface{}, not only Product.
I’v tried this, but result not resolved, this is the result
type AutoGenerated struct {
LayoutID int `json:"layoutID"`
Data []struct {
WidgetID int `json:"widgetID"`
Name string `json:"name"`
Type string `json:"type"`
Data []struct {
ProductID int `json:"productID"`
Name string `json:"name"`
} `json:"data"`
} `json:"data"`
}