簡體   English   中英

json:無法將數組解組為main類型的Go值

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

我正在嘗試使用golang讀取json文件,但出現此錯誤。 我已經檢查了幾乎所有有關此問題,但仍然無法解決。

這是示例json文件: https : //jsonplaceholder.typicode.com/posts

而我的代碼:

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)

}

JSON從根本上講就是一個數組。 您正在嘗試將其解組到一個對象,該對象包含一個作為字段的數組-因此,當JSON是數組時,傳遞對象的錯誤。 您想要傳遞一個數組(或實際上是切片),如下所示:

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是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