duanli9001 2017-06-05 07: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 07: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部