无法解码JSON响应。

huangapple go评论77阅读模式
英文:

Unable to decode the JSON response

问题

你可以使用标准库中的encoding/json包来解析JSON响应并获取Item数组。首先,你需要定义一个与JSON响应结构相匹配的结构体类型。在这种情况下,你可以定义一个名为Response的结构体,其中包含一个名为DataItem数组和一个名为Paging的结构体。

type Response struct {
   Data   []Item `json:"data"`
   Paging struct {
      Next string `json:"next"`
   } `json:"paging"`
}

type Item struct {
   Name string `json:"name"`
   Id   string `json:"id"`
}

然后,你可以使用json.Unmarshal函数将JSON响应解析为Response结构体实例。以下是一个示例代码:

import (
   "encoding/json"
   "fmt"
   "net/http"
   "io/ioutil"
)

func main() {
   // 假设你已经获取到了JSON响应的字节数据
   responseBytes := []byte(`{
      "data": [
         {
            "name": "Mohamed Galib",
            "id": "502008940"
         },
         {
            "name": "Mebin Joseph",
            "id": "503453614"
         },
         {
            "name": "Rohith Raveendranath",
            "id": "507482441"
         }
      ],
      "paging": {
         "next": "https://some_url"
      }
   }`)

   var response Response
   err := json.Unmarshal(responseBytes, &response)
   if err != nil {
      fmt.Println("解析JSON失败:", err)
      return
   }

   // 现在,你可以访问解析后的数据
   for _, item := range response.Data {
      fmt.Println("Name:", item.Name)
      fmt.Println("ID:", item.Id)
   }
}

这样,你就可以将JSON响应解析为Item数组,并对每个Item进行操作。

英文:

I have the following response from a graph api

{
   "data": [
      {
         "name": "Mohamed Galib",
         "id": "502008940"
      },
      {
         "name": "Mebin Joseph",
         "id": "503453614"
      },
      {
         "name": "Rohith Raveendranath",
         "id": "507482441"
      }
   ],
   "paging": {
      "next": "https://some_url"
   }
}

I have a struct as follows

type Item struct {
   Name, Id string
}

I wanted to parse the response and get an array of Item, How do I do that?

答案1

得分: 5

你需要像这样更新你的结构体:

type Item struct {
   Name string `json:"name"`
   Id string   `json:"id"`
}

并添加一个表示包装器的结构体:

type Data struct {
   Data []Item `json:"data"`
}

然后,你可以使用json.Unmarshal来填充一个Data实例。

在文档中可以查看示例

英文:

You need to update your struct like so:

type Item struct {
   Name string `json:"name"`
   Id string   `json:"id"`
}

and add a struct to represent the wrapper:

type Data struct {
   Data []Item `json:"data"`
}

You can then use json.Unmarshal to populate a Data instance.

See the example in the docs.

huangapple
  • 本文由 发表于 2014年1月14日 02:26:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/21098607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定