服务器正在发回这样的响应:
me@linux:~> curl -X GET http://*.*.*.*:8080/profiles
[
{
"ProfileID": 1,
"Title": "65micron"
},
{
"ProfileID": 2,
"Title": "80micron"
}
]
我试过了this solution将响应解析为 JSON,但它仅在服务器响应如下时有效:
{
"array": [
{
"ProfileID": 1,
"Title": "65micron"
},
{
"ProfileID": 2,
"Title": "80micron"
}
]
}
有人知道如何将服务器响应解析为 JSON 吗?
我想到的一个想法是将 { "array":
添加到 http.Response.Body
缓冲区的开头并添加 }
code> 到最后,然后使用 the standard solution .但是,我不确定这是否是最好的主意。
最佳答案
你可以直接解码成一个数组
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`
}
关于arrays - 解析服务器发送的数组/slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53692632/