代码之家  ›  专栏  ›  技术社区  ›  Megidd

正在分析服务器发送的数组/片

  •  0
  • Megidd  · 技术社区  · 7 年前

    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 缓冲区,并添加 } the standard solution . 然而,我不确定这是否是最好的主意。

    2 回复  |  直到 7 年前
        1
  •  2
  •   ssemilla    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`
    }
    

    Playground

        2
  •  1
  •   KibGzr    7 年前

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

    在解码响应之后

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