[英]golang : Unmarshal: json: cannot unmarshal array into Go value of type main.MonitorServerInfo
[英]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.