亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在下聯運期間處理不同類型的參數

在下聯運期間處理不同類型的參數

Go
RISEBY 2022-08-01 10:40:55
我正在使用弗里茨的一些API!Box router,我想在一個體面的結構中取消json響應,只需要找到一個好方法來做到這一點。有時在API響應中,WLan參數是boool,有時是這種類型的對象。// WLan contains info about the Wireless Lantype WLan struct {    Txt     string `json:"txt"`    Led     string `json:"led"`    Title   string `json:"title"`    Link    string `json:"link"`    Tooltip string `json:"tooltip"`}如果需要有關代碼的詳細信息,可以使用 github 存儲庫。我需要添加布爾wlan參數,我試圖復制“Data”結構并更改名稱,但該解決方案對我來說聽起來很糟糕。Wlan 包含在以下結構中:// Data contains data about the Fritz!Boxtype Data struct {    NasLink          string    `json:"naslink"`    FritzOS          FritzOS   `json:"fritzos"`    Webdav           int       `json:"webdav,string"`    Manual           string    `json:"MANUAL_URL"`    Language         string    `json:"language"`    AVM              string    `json:"AVM_URL"`    USBConnect       string    `json:"usbconnect"`    Foncalls         Foncalls  `json:"foncalls"`    VPN              VPN       `json:"vpn"`    Internet         Internet  `json:"internet"`    DSL              DSL       `json:"dsl"`    ServicePortalURL string    `json:"SERVICEPORTAL_URL"`    Comfort          Comfort   `json:"comfort"`    Changelog        Changelog `json:"changelog"`    TamCalls         TamCalls  `json:"tamcalls"`    Lan              External  `json:"lan"`    USB              External  `json:"usb"`    FonNum           External  `json:"fonnum"`    NewsURL          string    `json:"NEWSLETTER_URL"`    Net              Net       `json:"net"`    Dect             External  `json:"dect"`    WLan             WLan      `json:"wlan"`  //Wlan             bool      `json:"wlan"` # This is the other "case"}
查看完整描述

2 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

我不知道這是否是一個好的解決方案,我還是新手,但無論如何,你可以使用json。RawMessage并將財產的解封“延遲”到兩個單獨的結構字段之一。例如:wlan


package main


import (

    "encoding/json"

    "fmt"

)


// Data contains data about the Fritz!Box. (other fields omitted for brevity)

type Data struct {

    Language string           `json:"language"`

    NewsURL  string           `json:"NEWSLETTER_URL"`

    WLanRaw  *json.RawMessage `json:"wlan"`

    WLanBool bool             `json:"-"`

    WLanInfo *WLanInfo        `json:"-"`

}


// WLanInfo contains infos about the Wireless Lan

type WLanInfo struct {

    Txt     string `json:"txt"`

    Led     string `json:"led"`

    Title   string `json:"title"`

    Link    string `json:"link"`

    Tooltip string `json:"tooltip"`

}


func UnmarshalData(raw []byte, data *Data) error {

    if err := json.Unmarshal(raw, data); err != nil {

        return err

    }

    switch string(*data.WLanRaw) {

    case "true", "false":

        json.Unmarshal(*data.WLanRaw, &data.WLanBool)

    default:

        if err := json.Unmarshal(*data.WLanRaw, &data.WLanInfo); err != nil {

            return err

        }

    }

    return nil

}


func main() {

    jsonBool := []byte(`

{

    "language": "it",

    "NEWSLETTER_URL": "https://example.com/news",

    "wlan": true

}`)


    jsonInfo := []byte(`

{

    "language": "it",

    "NEWSLETTER_URL": "https://example.com/news",

    "wlan": {

        "txt": "footxt",

        "led": "fooled",

        "title": "hello",

        "link": "bar",

        "tooltip": "baz"

    }

}`)


    // error handling omitted

    var dataBool Data

    UnmarshalData(jsonBool, &dataBool)

    fmt.Printf("%+v\n\n", dataBool)


    var dataInfo Data

    UnmarshalData(jsonInfo, &dataInfo)

    fmt.Printf("%+v %+v\n", dataInfo, dataInfo.WLanInfo)

}

$ go build fritz.go

$ ./fritz

{Language:it NewsURL:https://example.com/news WLanRaw:0xc0000a4060 WLanBool:true WLanInfo:<nil>}


{Language:it NewsURL:https://example.com/news WLanRaw:0xc0000a4080 WLanBool:false WLanInfo:0xc0000b0000} &{Txt:footxt Led:fooled Title:hello Link:bar Tooltip:baz}

$


查看完整回答
反對 回復 2022-08-01
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

你可以實現 json。Unmarshaler 和 json.封送線接口。


type WLan struct {

    Bool    *bool  `json:"-"`

    Txt     string `json:"txt"`

    Led     string `json:"led"`

    Title   string `json:"title"`

    Link    string `json:"link"`

    Tooltip string `json:"tooltip"`

}


// implements json.Unmarshaler

func (w *WLan) UnmarshalJSON(data []byte) error {

    if len(data) > 0 && (data[0] == 't' || data[0] == 'f') { // seems to be a bool

        w.Bool = new(bool)

        return json.Unmarshal(data, w.Bool)

    }

    if len(data) > 1 && data[0] == '{' && data[len(data)-1] == '}' { // it's an object

        // type W and the conversion (*W)(w) are required to

        // prevent encoding/json from invoking the UnmarshalJSON

        // method recursively causing a stack overflow

        type W WLan

        return json.Unmarshal(data, (*W)(w))

    }

    return nil // or error, up to you

}


// implements json.Marshaler

func (w WLan) MarshalJSON() ([]byte, error) {

    if w.Bool != nil {

        return json.Marshal(*w.Bool)

    }

    // Same as with UnmarshalJSON, type W and the conversion W(w) are 

    // required to prevent encoding/json from invoking the MarshalJSON

    // method recursively causing a stack overflow

    type W WLan

    return json.Marshal(W(w))

}

https://play.golang.org/p/s72zt4ny7Pv


查看完整回答
反對 回復 2022-08-01
  • 2 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號