json解组嵌入式结构 [英] json unmarshal embedded struct

查看:107
本文介绍了json解组嵌入式结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解组定义为的结构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{})似乎仅使用InnerUnmarshalJSON,而忽略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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆