猿问

如何在解组 JSON 时检查提供的 api 字段的类型

如何解组 JSON 响应,其中空字段值作为字符串从服务器返回,而其他时间作为对象返回?


{

"replies": "" // empty field from server

}

服务器有一些回复



    {

    "replies": {

    "author" : "fooname"

    }

    }


golang 解组错误,因为无法将字符串转换为类型


人到中年有点甜
浏览 145回答 2
2回答

慕工程0101907

正如评论中提到的,您需要实现json.Unmarshaler接口来处理这种情况。假设我们从这些结构开始,我们可以看到需要自定义逻辑的字段类型为Replies:type Response struct {    Replies Replies `json:"replies"`}type Replies struct {    *realResp}// Contains actual datatype 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.您还可以查看此完整示例。

阿晨1998

由于 golang 是严格类型的,回复不能有 2 种类型(字符串和对象)如果没有,回复应该返回一个对象或 null。此代码可能有助于理解。package mainimport (    "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")    }}
随时随地看视频慕课网APP

相关分类

Go
我要回答