2

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.

1
  • Do you want to unmarshal object like linked-list? Commented Jun 30, 2017 at 9:14

1 Answer 1

4

*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]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.