2 回答

TA贡献1887条经验 获得超5个赞
正如评论中提到的,您需要实现json.Unmarshaler接口来处理这种情况。
假设我们从这些结构开始,我们可以看到需要自定义逻辑的字段类型为Replies:
type Response struct {
Replies Replies `json:"replies"`
}
type Replies struct {
*realResp
}
// Contains actual data
type realResp struct {
Author string `json:"author"`
}
现在我们可以实现该UnmarshalJSON方法:
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)
}
注意指针接收器,以便 UnmarshalJSON 可以修改r.
您还可以查看此完整示例。

TA贡献2037条经验 获得超6个赞
由于 golang 是严格类型的,回复不能有 2 种类型(字符串和对象)
如果没有,回复应该返回一个对象或 null。此代码可能有助于理解。
package main
import (
"encoding/json"
"fmt"
)
type replies struct {
Author string `json:"author"`
}
type resp struct {
Replies *replies `json:"replies"`
}
func main() {
obj := new(resp)
response := []byte(`{"replies": {"author":"fooname"}}`)
//response := []byte(`{"replies": null}`)
err := json.Unmarshal(response, obj)
if err != nil {
fmt.Println(err)
}
if obj.Replies != nil {
fmt.Println(obj.Replies.Author)
} else {
fmt.Println("Empty replies")
}
}
- 2 回答
- 0 关注
- 144 浏览
添加回答
举报