第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

使用 json.RawMessage 將 json 解組為結(jié)構(gòu)

使用 json.RawMessage 將 json 解組為結(jié)構(gòu)

Go
牛魔王的故事 2022-03-07 16:00:29
我需要解組可能具有以下格式的 json 對(duì)象:-Format1:    {    "contactType": 2,    "value": "0123456789"    }Format2:    {    "contactType": "MobileNumber",    "value": "0123456789"    }我用于解組的結(jié)構(gòu)是:-    type Contact struct {    ContactType int    `json:"contactType"`     Value       string `json:"value"`    }但這僅適用于格式 1。我不想更改 ContactType 的數(shù)據(jù)類型,但我也想適應(yīng)第二種格式。我聽說過 json.RawMarshal 并嘗試使用它。    type Contact struct {        ContactType        int        Value       string          `json:"value"`        Type json.RawMessage `json:"contactType"    }    type StringContact struct {    Type string `json:"contactType"`    }    type IntContact struct {    Type int `json:"contactType"`    } 這完成了解組,但我無法設(shè)置取決于 json.RawMessage 類型的 ContactType 變量。如何為我的結(jié)構(gòu)建模以便解決這個(gè)問題?
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊

您需要自己進(jìn)行解組。有一篇非常好的文章展示了如何使用 json.RawMessage 權(quán)利和許多其他解決這個(gè)問題的方法,比如使用接口、RawMessage、實(shí)現(xiàn)你自己的解組和解碼函數(shù)等。


您可以在此處找到文章:Attila Oláh 在 GO 中的 JSON 解碼 注意:Attila 在他的代碼示例中犯了一些錯(cuò)誤。


我冒昧地整理了一個(gè)工作示例(使用 Attila 的一些代碼),它使用 RawMessage 來延遲解組,以便我們可以在我們自己的 Decode func 版本上進(jìn)行。


鏈接到 GOLANG 游樂場(chǎng)


package main


import (

    "fmt"

    "encoding/json"

    "io"

)


type Record struct {

    AuthorRaw json.RawMessage `json:"author"`

    Title     string          `json:"title"`

    URL       string          `json:"url"`


    Author Author

}


type Author struct {

    ID    uint64 `json:"id"`

    Email string `json:"email"`

}


func Decode(r io.Reader) (x *Record, err error) {

    x = new(Record)

    if err = json.NewDecoder(r).Decode(x); err != nil {

        return

    }

    if err = json.Unmarshal(x.AuthorRaw, &x.Author); err == nil {

        return

    }

    var s string

    if err = json.Unmarshal(x.AuthorRaw, &s); err == nil {

        x.Author.Email = s

        return

    }

    var n uint64

    if err = json.Unmarshal(x.AuthorRaw, &n); err == nil {

        x.Author.ID = n

    }

    return

}


func main() {


    byt_1 := []byte(`{"author": 2,"title": "some things","url": "https://stackoverflow.com"}`)


    byt_2 := []byte(`{"author": "Mad Scientist","title": "some things","url": "https://stackoverflow.com"}`)


    var dat Record


    if err := json.Unmarshal(byt_1, &dat); err != nil {

            panic(err)

    }

    fmt.Printf("%#s\r\n", dat)


    if err := json.Unmarshal(byt_2, &dat); err != nil {

            panic(err)

    }

    fmt.Printf("%#s\r\n", dat)

}

希望這可以幫助。


查看完整回答
反對(duì) 回復(fù) 2022-03-07
  • 1 回答
  • 0 關(guān)注
  • 273 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)