[英]Parsing an array/slice sent by server
服務器正在發送回這樣的響應:
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嗎?
我想到的一個主意是在http.Response.Body
緩沖區的開頭添加{ "array":
http.Response.Body
並在末尾添加}
,然后使用標准解決方案 。 但是,我不確定這是否是最好的主意。
您可以直接將其解組到數組中
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`
}
您應該定義一個結構
type Profile struct {
ID int `json:"ProfileID"`
Title string `json:"Title"`
}
之后,解碼響應
var r []Profile
err := json.NewDecoder(res.Body).Decode(&r)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.