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

htunc:

我正在尝试使用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)

}
htkaya:

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)

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

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

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

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

json:无法将字符串解组为main.test_struct类型的Go值

json:无法将字符串解组为[] main.KVU类型的Go值

Docker返回“ json:无法将字符串解组为[] string类型的Go值”

将JSON解组到struct:无法将数组解组到Go值

json:无法将对象解组为具有某些值的类型错误的Go值

无法将字符串解组为int64类型的Go值

Golang-无法将数字解组为字符串类型的Go值

无法将字符串解组为struct类型的Go值

JSON无法将对象解组为字符串类型的GO值

json:无法将对象解组为Auction.Item类型的Go值

将JSON解组为类型

得到:无法将字符串解组为Go值

json错误,无法将对象解组为Go值

json:无法将数字5088060241解组为int类型的结构

docker:OCI运行时创建失败:json:无法将对象解组为[]类型的Go值string:未知

无法将json数据解组到go中的结构(无法将数组解组到Go struct字段中)

将json数组解组为struct数组

无法将数字解组为Go Value

golang json数组解组为struct类型

将JSON数组解组为JSON对象

将JSON解组为UUID类型

将JSON解组为最小类型

无法将对象解组为[] uint8类型的Go值

如何将值解组为 map[string][int] 类型的 json 结构

将 JSON 数组解组为指针切片时跳过空值

将科学概念中的值解组为 Go 中的整数