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

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

處理不同類型的請求正文

處理不同類型的請求正文

Go
翻閱古今 2023-07-31 17:13:20
假設(shè)后端應(yīng)用程序有這樣的請求。正如您所看到的,這是一個對象數(shù)組。[    {        "section_id": "8ad1f7cc-a510-48ee-b4fa-bedbee444a84", // (uuid - string)        "section_name": "First section"    },    {        "section_id": 1556895, // (int)        "section_name": "Second section"    }]我想解析這個數(shù)組。根據(jù)部分 ID 類型,應(yīng)用程序需要執(zhí)行不同的操作。如何繞過嚴(yán)格輸入?requestBody, err := ioutil.ReadAll(request.Body)if err = json.Unmarshal([]byte(requestBody), &sections); err != nil {    println(err)}for _, section := range sections {    if reflect.TypeOf(section.ID) == string {        // block 1    } reflect.TypeOf(section.ID) == int {        // block 2    }}
查看完整描述

2 回答

?
忽然笑

TA貢獻(xiàn)1806條經(jīng)驗 獲得超5個贊

你可以嘗試用這個:


type section struct {

    ID interface{} `json:"section_id"`

    Name string `json:"section_name"`

}


dec := json.NewDecoder(requestBody)

dec.UseNumber()

var sections []section

if err := dec.Decode([]byte(request.Body), &sections); err != nil {

    println(err)

}


for _, section := range sections {

    if reflect.TypeOf(section.ID).String() == "string" {

        // block 1

    } reflect.TypeOf(section.ID).String() == "json.Number" {

        n := section.ID.Int64()

        // block 2

    }

}



查看完整回答
反對 回復(fù) 2023-07-31
?
慕仙森

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊

有幾種方法可以做到這一點:


type Section struct {

   ID interface{} `json:"section_id"`

   SectionName string `json:"section_name"

}


for _, section := range sections {

   if str,ok:=section.ID.(string); ok {

   } else if number, ok:=section.ID.(float64); ok {

   }

}

或者:


type Section struct {

   ID json.RawMessage `json:"section_id"`

   SectionName string `json:"section_name"

}


for _, section := range sections {

   if value, err:=strconv.Atoi(string(section.ID)); err==nil {


   } else {

   }

}


查看完整回答
反對 回復(fù) 2023-07-31
  • 2 回答
  • 0 關(guān)注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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