【问题标题】:Parsing an array/slice sent by server解析服务器发送的数组/切片
【发布时间】:2018-12-09 21:55:18
【问题描述】:

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

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。但是,我不确定这是否是最好的主意。

【问题讨论】:

  • 您的 json 无效,您在对象末尾添加了一个额外的 ','。您可以使用jsonlint.com 对其进行验证。更正它并重试
  • @AhmedEssam 谢谢,我的 JSON 非常长。我刚刚在这里粘贴了两个键/值作为示例,我忘记删除多余的 , 我现在要解决我的问题

标签: arrays json go


【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多