为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
人到中年有点甜 2022-04-26 20:00:59
如何解组 JSON 响应,其中空字段值作为字符串从服务器返回,而其他时间作为对象返回?{"replies": "" // empty field from server}服务器有一些回复    {    "replies": {    "author" : "fooname"    }    }golang 解组错误,因为无法将字符串转换为类型
查看完整描述

2 回答

?
慕工程0101907

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.


您还可以查看此完整示例。


查看完整回答
反对 回复 2022-04-26
?
阿晨1998

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")

    }

}


查看完整回答
反对 回复 2022-04-26
  • 2 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号