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

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

在 Go 中解組頂級(jí) JSON 數(shù)組

在 Go 中解組頂級(jí) JSON 數(shù)組

Go
人到中年有點(diǎn)甜 2021-08-16 19:58:36
我正在通過編寫一個(gè)簡(jiǎn)單的 http 服務(wù)器來(lái)學(xué)習(xí) Go,我需要處理一些 JSON 響應(yīng)。使用對(duì)象響應(yīng),我可以用 2 行代碼慣用地解組它: structResult := Foo{} json.Unmarshal(structBody, &structResult)我不知道如何對(duì)數(shù)組響應(yīng)執(zhí)行相同的操作(請(qǐng)參見下面的示例)。有沒有辦法指定(可能通過 json 標(biāo)簽)頂級(jí)數(shù)組應(yīng)該進(jìn)入給定的結(jié)構(gòu)字段?package mainimport "fmt"import "encoding/json"type Foo struct {    Id uint64 `json:"id"`    Name string `json:"name"`}type BaseResult struct {    Error string  `json:"error"`}type FooResult struct {    BaseResult    Foos []Foo}func main() {    // Simple and works.    structBody := []byte(`{"id": 1,"name": "foo"}`)    structResult := Foo{}    json.Unmarshal(structBody, &structResult)    fmt.Printf("%#v\n", structResult)    // Doesn't work.    arrayBody := []byte(`[{"id": 1,"name": "foo"},{"id": 2,"name": "bar"},{"id": 3,"name": "foobar"}]`)     arrayResult := FooResult{}    json.Unmarshal(arrayBody, &arrayResult)    fmt.Printf("%#v\n", arrayResult)}我知道我可以讓 FooResult 成為一個(gè)數(shù)組:type FooResult []Foo但后來(lái)我失去了指定基礎(chǔ)對(duì)象的能力,我想用它來(lái)存儲(chǔ)錯(cuò)誤消息等。我也知道我可以直接解組到 &fooResult.Foos 中,但我希望代碼能夠同時(shí)處理對(duì)象和數(shù)組。更新按照@dyoo 的建議實(shí)現(xiàn) UnmarshalJSON 部分解決了我的問題,但我希望我可以使用 BaseResult 來(lái)存儲(chǔ)解析錯(cuò)誤,以防 JSON 具有不同的結(jié)構(gòu):arrayBody := []byte(`{"error": "foo"}`)arrayResult := FooResult{}json.Unmarshal(arrayBody, &arrayResult)fmt.Printf("%#v\n", arrayResult)當(dāng)然,我可以在 UnmarshalJSON 中實(shí)現(xiàn)更復(fù)雜的邏輯 - 但沒有更簡(jiǎn)單的方法來(lái)做到這一點(diǎn)嗎?
查看完整描述

2 回答

?
qq_遁去的一_1

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

只需指定Foos何時(shí)解組


package main


import "fmt"

import "encoding/json"


type Foo struct {

    Id   uint64 `json:"id"`

    Name string `json:"name"`

}


type BaseResult struct {

    Error string `json:"error"`

}


type FooResult struct {

    BaseResult

    Foos []Foo

}


func main() {

    // Simple and works.

    structBody := []byte(`{"id": 1,"name": "foo"}`)

    structResult := Foo{}

    json.Unmarshal(structBody, &structResult)

    fmt.Printf("%#v\n", structResult)


    // Doesn't work.

    arrayBody := []byte(`[{"id": 1,"name": "foo"},{"id": 2,"name": "bar"},{"id": 3,"name": "foobar"}]`)

    arrayResult := FooResult{}

    if err := json.Unmarshal(arrayBody, &arrayResult.Foos); err != nil {

        arrayResult.BaseResult.Error = string(arrayBody)

    }


    fmt.Printf("%#v\n", arrayResult)

}


查看完整回答
反對(duì) 回復(fù) 2021-08-16
  • 2 回答
  • 0 關(guān)注
  • 243 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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