rafaelmaeuer
11/11/2019 - 12:23 PM

How to Unmarshal an inconsistent JSON field that can be a string *or* an array of string?

type MyListItem struct {
    Date           string      `json:"date"`
    DisplayName    string      `json:"-"`
    RawDisplayName interface{} `json:"display_name"`
}

func (li *MyListItem) UnmarshalJSON(data []byte) error {
    type localItem MyListItem
    var loc localItem
    if err := json.Unmarshal(data, &loc); err != nil {
        return err
    }
    *li = MyListItem(loc)
    switch li.RawDisplayName.(type) {
    case string:
        li.DisplayName = li.RawDisplayName.(string)
    case []interface{}:
        vals := li.RawDisplayName.([]interface{})
        if len(vals) > 0 {
            li.DisplayName, _ = vals[0].(string)
            for _, v := range vals[1:] {
                li.DisplayName += "&" + v.(string)
            }
        }
    }
    return nil
}