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

前端 未结 3 1702
渐次进展
渐次进展 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:35

    You can have your item type implement the json.Unmarshaler interface.

    func (i *item) UnmarshalJSON(data []byte) error {
        if string(data) == `""` {
            return nil
        }
    
        type tmp item
        return json.Unmarshal(data, (*tmp)(i))
    }
    

    https://play.golang.org/p/1TrD57XULo9

提交回复
热议问题