Reputation: 527
I have a struct as below:
type Item struct {
ID int16 `json:"id"`
SubItem *Item `json:"sub_item"`
}
And the JSON as below:
{
"id": 100,
"sub_item": 110
}
If I use json.Unmarshal(json, &item)
, the json field sub_item
is the Item.ID
, so cannot mapping into struct.
I want to find the SubItem by the subitem id before json unmarshal, but I don't know how to do it. Or is there any way to resolve this problem? thanks a lot.
Upvotes: 2
Views: 264
Reputation: 96
*Item
is a golang pointer to a struct. It cannot contain a int16
(that is a "pointer" in your json semantic).
You can handle this programmatically after Unmarshaling.
Struct must be:
type Item struct {
ID int16 `json:"id"`
SubItem *Item
SubItemInt int16 `json:"sub_item"`
}
and then you should do something like this:
items := make(map[int16]*Item)
[...]
for k := range items {
items[k].SubItem = items[items[k].SubItemInt]
}
Upvotes: 4