As mentioned in the comments, you need to implement the json.Unmarshaler
interface to handle this case.
Assuming we start with these structs, we can see that the field that needs custom logic is of type Replies
:
type Response struct {
Replies Replies `json:"replies"`
}
type Replies struct {
*realResp
}
// Contains actual data
type realResp struct {
Author string `json:"author"`
}
Now we can implement the UnmarshalJSON
method:
func (r *Replies) UnmarshalJSON(b []byte) error {
if string(b) == "\"\"" {
return nil // Do nothing; you might also want to return an error
}
r.realResp = &realResp{} // Initialize r.realResp
return json.Unmarshal(b, r.realResp)
}
Note the pointer receiver so UnmarshalJSON can modify r
.
You can also see this full example.