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

huangapple go评论82阅读模式
英文:

Cannot unmarshal object into Go value of type []uint8

问题

我对Go相当新手。我有以下代码:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
    dat := []byte(`{"num":7.13,"strs":["c","d"]}`)
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)

}

出现了以下错误:

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

请问我该如何修复这个问题?

英文:

I am fairly new to Go. I have the following code:

package main

import (
    "encoding/json"
    "fmt"
)
func main() {

	byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
	dat := []byte(`{"num":7.13,"strs":["c","d"]}`)
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}
	fmt.Println(dat)

}

Getting the error:

> cannot "unmarshal object into Go value of type []uint8".

How can I fix this please?

答案1

得分: 9

你有两个JSON输入,并且你试图将一个解组成另一个。这没有任何意义。

使用一个类型(结构体)对你的JSON输入(对象)进行建模,并将其解组成该类型。例如:

type Obj struct {
    Num  float64  `json:"num"`
    Strs []string `json:"strs"`
}

func main() {
    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

    var obj Obj
    if err := json.Unmarshal(byt, &obj); err != nil {
        panic(err)
    }
    fmt.Println(obj)
}

输出结果(在Go Playground上尝试):

{6.13 [a b]}
英文:

You have 2 JSON inputs, and you're trying to unmarshal one into the other. That doesn't make any sense.

Model your JSON input (the object) with a type (struct), and unmarshal into that. For example:

type Obj struct {
	Num  float64  `json:"num"`
	Strs []string `json:"strs"`
}

func main() {
	byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

	var obj Obj
	if err := json.Unmarshal(byt, &obj); err != nil {
		panic(err)
	}
	fmt.Println(obj)

}

Output (try it on the Go Playground):

{6.13 [a b]}

答案2

得分: 2

我认为你的意思是这样的:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var dat interface{}
	byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}
	fmt.Println(dat)
}

你尝试的操作没有意义,因为你试图将一个 JSON 对象解组成另一个 JSON 对象。

英文:

I think you meant to do something like this:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var dat interface{}
	byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}
	fmt.Println(dat)
}

What you were trying to do makes no sense, since you're trying to unmarshal two JSON objects one into another.

huangapple
  • 本文由 发表于 2017年6月6日 16:37:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/44385203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定