简体   繁体   English

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

[英]json: cannot unmarshal array into Go value of type main.Posts

I'm trying to read a json file with golang but i'm getting this error. 我正在尝试使用golang读取json文件,但出现此错误。 I've checked almost every question about it but still couldnt get it. 我已经检查了几乎所有有关此问题,但仍然无法解决。

Here's the example json file: https://jsonplaceholder.typicode.com/posts 这是示例json文件: 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)

}

That JSON is, at its root, an array. JSON从根本上讲就是一个数组。 You're trying to unmarshal it into an object, which contains, as a field, an array - hence the error that you passed an object when the JSON is an array. 您正在尝试将其解组到一个对象,该对象包含一个作为字段的数组-因此,当JSON是数组时,传递对象的错误。 You want to pass an array (or slice, really), as in: 您想要传递一个数组(或实际上是切片),如下所示:

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

//...

var posts []Post
err := json.Unmarshal([]byte(content), &posts)

// Check err, do stuff with posts

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. Posts是Post结构的数组,但您将Post定义为数组是您的第一个错误,Unmarshal也不返回结果,它仅返回错误并填充给定参数。

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)

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM