2017-06-05 103 views
0

我試圖用golang讀取json文件,但是我收到了這個錯誤。 我已經檢查了幾乎所有關於它的問題,但仍然無法得到它。json:can not unmarshal array Go類型的值main.Posts

這裏的例子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) 

} 

回答

1

帖子是郵政的陣列結構,但你定義爲後陣是你的第一個錯誤,也解組沒有返回結果它只返回錯誤並填充給定的參數。

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) 

} 
3

即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