duanli9001 2017-06-05 15:02
浏览 27
已采纳

json:无法将数组解组为main类型的Go值

I'm trying to read a json file with golang but i'm getting this error. I've checked almost every question about it but still couldnt get it.

Here's the example json file: https://jsonplaceholder.typicode.com/posts

And my code:

package main

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

type Posts struct {
    Post []struct{
        UserId int `json:"userId"`
        ID int `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
    }
}

func main (){
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")

    if err != nil {
        log.Fatal(err)
    }

    content, _ := ioutil.ReadAll(resp.Body)

    var posts Posts

    parsed := json.Unmarshal([]byte(content), &posts)

    //fmt.Println(string(content))

    fmt.Println(parsed)

}
  • 写回答

2条回答 默认 最新

  • dongya4089 2017-06-05 15:16
    关注

    Posts is an array of Post struct but you defined Post as array it is your first mistake, also Unmarshal doesn't returns result it returns only error and fills given parameter.

    package main
    
    import (
        "net/http"
        "log"
        "fmt"
        "io/ioutil"
        "encoding/json"
    )
    
    type Post struct {
            UserId int `json:"userId"`
            ID int `json:"id"`
            Title string `json:"title"`
            Body string `json:"body"`
    }
    
    type Posts []Post
    
    
    func main (){
        resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
    
        if err != nil {
            log.Fatal(err)
        }
    
        content, _ := ioutil.ReadAll(resp.Body)
    
        var posts Posts
    
        err = json.Unmarshal(content, &posts)
    
        if err != nil {
            log.Fatal(err)
        }
    
    
        fmt.Println(posts[0].Body)
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?