首页 文章

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

提问于
浏览
0

服务器正在发回这样的响应:

me@linux:~> curl -X GET http://*.*.*.*:8080/profiles

[
        {
                "ProfileID": 1,
                "Title": "65micron"
        },
        {
                "ProfileID": 2,
                "Title": "80micron"
        }
]

我已经尝试this solution将响应解析为JSON,但如果服务器响应是这样的话, only 可以工作:

{
    "array": [
        {
                "ProfileID": 1,
                "Title": "65micron"
        },
        {
                "ProfileID": 2,
                "Title": "80micron"
        }
    ]
}

有谁知道如何将服务器响应解析为JSON?


我想到的一个想法是将 { "array": 添加到 http.Response.Body 缓冲区的开头并将 } 添加到其结尾,然后使用the standard solution . 但是,我最好的主意 .

2 回答

  • 1

    您可以直接解组到数组中

    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`
    }
    

    Playground

  • 2

    你应该定义一个结构

    type Profile struct {
        ID int `json:"ProfileID"`
        Title string `json:"Title"`
    }
    

    之后解码响应

    var r []Profile
    err := json.NewDecoder(res.Body).Decode(&r)
    

相关问题