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

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

解析服務器發送的數組/切片

解析服務器發送的數組/切片

Go
一只甜甜圈 2023-05-15 14:58:01
服務器正在發回這樣的響應:me@linux:~> curl -X GET http://*.*.*.*:8080/profiles[        {                "ProfileID": 1,                "Title": "65micron"        },        {                "ProfileID": 2,                "Title": "80micron"        }]我已嘗試使用此解決方案將響應解析為 JSON,但僅當服務器響應如下所示時才有效:{    "array": [        {                "ProfileID": 1,                "Title": "65micron"        },        {                "ProfileID": 2,                "Title": "80micron"        }    ]}有人知道我如何將服務器響應解析為 JSON 嗎?我想到的一個想法是添加{ "array":到緩沖區的開頭http.Response.Body并添加}到它的結尾,然后使用標準解決方案。但是,我不確定這是否是最好的主意。
查看完整描述

2 回答

?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

您可以直接解組為數組


data := `[

    {

        "ProfileID": 1,

        "Title": "65micron"

    },

    {

        "ProfileID": 2,

        "Title": "80micron"

    }]`


type Profile struct {

    ProfileID int

    Title     string

}


var profiles []Profile


json.Unmarshal([]byte(data), &profiles)

您也可以直接從Request.Body.


func Handler(w http.ResponseWriter, r *http.Request) {


    var profiles []Profile

    json.NewDecoder(r.Body).Decode(&profiles)

    // use `profiles`

}

操場


查看完整回答
反對 回復 2023-05-15
?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

你應該定義一個結構


type Profile struct {

    ID int `json:"ProfileID"`

    Title string `json:"Title"`

}

在解碼響應之后


var r []Profile

err := json.NewDecoder(res.Body).Decode(&r)


查看完整回答
反對 回復 2023-05-15
  • 2 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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