json解组嵌入式结构 [英] json unmarshal embedded struct
问题描述
我想解组定义为的结构Outer
:
I would like to unmarshal to struct Outer
defined as:
type Outer struct {
Inner
Num int
}
type Inner struct {
Data string
}
func (i *Inner) UnmarshalJSON(data []byte) error {
i.Data = string(data)
return nil
}
使用json.Unmarshal(data, &Outer{})
似乎仅使用Inner
的UnmarshalJSON
,而忽略Num
字段:
Using json.Unmarshal(data, &Outer{})
seems only to use Inner
's UnmarshalJSON
and ignores the Num
field: https://play.golang.org/p/WUBfzpheMl
我有一个笨拙的解决方案,我在其中手动设置了Num
字段,想知道是否有人有一种更清洁或更简单的方法.
I have an unwieldy solution where I set the Num
field manually, but I was wondering if anybody had a cleaner or simpler way to do it.
谢谢!
推荐答案
之所以发生这种情况,是因为Inner
被嵌入在Outer
中.这意味着当json库在Outer
上调用unmarshaler时,它最终会在Inner
上调用它.
This is happening because Inner
is being embedded in Outer
. That means when json library calls unmarshaler on Outer
, it instead ends up calling it on Inner
.
因此,在func (i *Inner) UnmarshalJSON(data []byte)
内,data
参数包含整个json字符串,然后仅对Inner
进行处理.
Therefore, inside func (i *Inner) UnmarshalJSON(data []byte)
, the data
argument contains the entire json string, which you are then processing for Inner
only.
您可以通过在Outer
Outer struct {
I Inner // make Inner an explicit field
Num int `json:"Num"`
}
这篇关于json解组嵌入式结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!