当前位置: > > > > 解析服务器发送的数组/切片
解析服务器发送的数组/切片
来源:stackoverflow
2024-04-22 19:15:35
0浏览
收藏
一分耕耘,一分收获!既然都打开这篇《解析服务器发送的数组/切片》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
问题内容
服务器正在发回这样的响应:
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 缓冲区的开头,并将 } 添加到其末尾,然后使用标准解决方案。但是,我不确定这是否是最好的主意。
解决方案
您可以直接解组到数组中
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)
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《解析服务器发送的数组/切片》文章吧,也可关注米云公众号了解相关技术文章。
