为了账号安全,请及时绑定邮箱和手机立即绑定

解析服务器发送的数组/切片

解析服务器发送的数组/切片

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 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信