how to unmarshal json object if object is returning as empty string instead of empty struct

前端 未结 3 1690
渐次进展
渐次进展 2021-01-27 17:27

I\'m receiving some data as JSON, but if a object is empty, it does not return a empty struct but a empty string instead, and when unmarshaling, it returns an error.

So

3条回答
  •  北海茫月
    2021-01-27 17:53

    Create a type like type ItemOrEmptyString item

    And implement Unmarshal interface for it to handle your custom case.

    func(ies *ItemOrEmptyString)UnmarshalJSON(d []byte) error{
        var i item
        if string(d) == `""` {
           return nil
        }
        err := json.Unmarshal(d, &i)
        *ies  = ItemOrEmptyString(i)
        return err
    }
    

    Full code here

提交回复
热议问题