Golang将JSON映射到结构体

huangapple go评论66阅读模式
英文:

Golang mapping JSON into struct

问题

我有一个如下的结构体:

type Item struct {
  ID         int16 `json:"id"`
  SubItem    *Item `json:"sub_item"`
}

还有以下的JSON:

{
  "id": 100,
  "sub_item": 110
}

如果我使用json.Unmarshal(json, &item),JSON字段sub_item会映射到Item.ID,因此无法映射到结构体。

我想在JSON解析之前通过子项ID找到SubItem,但我不知道如何做。或者是否有任何方法解决这个问题?非常感谢。

英文:

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

得分: 4

*Item是一个指向结构体的golang指针。它不能包含int16(在你的JSON语义中是一个“指针”)。

你可以在解析后通过编程的方式处理这个问题。

结构体应该是这样的:

type Item struct {
    ID         int16 `json:"id"`
    SubItem    *Item
    SubItemInt int16 `json:"sub_item"`
}

然后你可以这样做:

items := make(map[int16]*Item)
// ...
for k := range items {
    items[k].SubItem = items[items[k].SubItemInt]
}

希望对你有帮助!

英文:

*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]
}

huangapple
  • 本文由 发表于 2017年6月30日 17:07:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/44842722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定