arrays - 解析服务器发送的数组/slice

标签 arrays json go

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

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 缓冲区的开头并添加 } code> 到最后,然后使用 the standard solution .但是,我不确定这是否是最好的主意。

最佳答案

你可以直接解码成一个数组

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

关于arrays - 解析服务器发送的数组/slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53692632/

相关文章:

java - 在Java中初始化Map的静态数组

android - 尝试创建一个对象数组

c# - 将结构数组从 C# 传递到 C++ DLL

json - 找不到可接受的代表

go - 如何使用 Sarama Go Kafka Consumer 从最新的偏移量中消费

database - 从 PostGres 数据库获取结构

java - Java 中 array.length() 的内部代码是什么?

javascript - 如何使用 JSON-LD 标记面包屑列表中的最后一个非链接项

json - Watson Conversation - 从嵌套上下文中检索特定数据

其他包中未定义 html/template 类型的 Golang 全局变量