dtah63820 2017-06-29 13:23
浏览 154
已采纳

包含接口列表的结构上的UnmarshalJSON

I would like to UnmarshalJSON a struct containing an interface as follows:

type Filterer interface {
    Filter(s string) error
}

type FieldFilter struct {
    Key string
    Val string
}    

func (ff *FieldFilter) Filter(s string) error {
    // Do something
}

type Test struct {
    Name string
    Filters []Filterer
}

My idea was to send a json like so:

{
    "Name": "testing",
    "Filters": [
        {
            "FieldFilter": {
                "Key": "key",
                "Val": "val"
            }
        }
    ]
}

However, when sending this json to the unmarshaler, the following exception returns: json: cannot unmarshal object into Go struct field Test.Filters of type Filterer

I understand the problem fully, but do not know how to approach this problem wisely. Looking for advice on an idiomatic way to solving this problem in go.

  • 写回答

2条回答 默认 最新

  • drkjzk3359 2017-07-16 12:36
    关注

    Following my own question, I researched how one could implement UnmarshalJSON for interface lists. Ultimately this led me to publish a blog post on how to do this properly. Basically there are 2 main solutions:

    1. Parse the required JSON string into a map[string]*json.RawMessage and work your way from there.
    2. Make an alias for the interface list and implement UnmarshalJSON for that alias. However, you'll still need to work with map[string]*json.RawMessage and some manual work. Nothing comes without a price!

    I highly suggest taking the seconds approach. While these two solutions may result in the same amount of code lines, taking advantage of type aliasing and being less dependent on json.RawMessage types will make a more easy to manage code, especially when it is required to support multiple interfaces on the UnmarshalJSON implementation

    To directly answer the question, start with making a type alias for the interface list:

    type Filterers []Filterer
    

    Now continue with implementing the decoding of the JSON:

    func (f *Filterers) UnmarshalJSON(b []byte) error {
        var FilterFields map[string]*json.RawMessage
        if err := json.Unmarshal(b, &FilterFields); err != nil {
            return err
        }
        for LFKey, LFValue := range FilterFields {
            if LFKey == "FieldFilter" {
                var MyFieldFilters []*json.RawMessage
                if err := json.Unmarshal(*LFValue, &MyFieldFilters); err != nil {
                    return err
                }
                for _, MyFieldFilter := range MyFieldFilters {
                    var filter FieldFilter
                    if err := json.Unmarshal(*MyFieldFilter, &filter); err != nil {
                        return err
                    }
                    *f = append(*f, &filter)
                }
            }
        }
        return nil
    }
    

    A detailed explanation (with some examples and a full working code snippets) of the second approach is available on my own blog

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵
  • ¥15 cfx离心泵非稳态计算