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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址