Unmarshalling a JSON that may or may not return an array?

后端 未结 2 775
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 19:33

I\'m retrieving JSON from a third party website (home electricity usage), and depending on what I\'ve requested from the site, the JSON returned may or may not be an array.

2条回答
  •  猫巷女王i
    2020-12-06 19:55

    You can try to make custom json unmarshal method, like

    func (a *GwrcmCustom) UnmarshalJSON(b []byte) (err error) {
        g, ga := Gwrcmd{}, []Gwrcmd{}
        if err = json.Unmarshal(b, &g); err == nil {
            *a = make([]Gwrcmd, 1)
            []Gwrcmd(*a)[0] = Gwrcmd(g)
            return
        }
        if err = json.Unmarshal(b, &ga); err == nil {
            *a = GwrcmCustom(ga)
            return
        }
        return
    }
    

    GwrcmCustom is a custom type, slice of Gwrcm

    type GwrcmCustom []Gwrcmd
    

    So we will get slice always

    Try this on Go playground

    I hope this will help

提交回复
热议问题