![](/img/trans.png)
[英]json: cannot unmarshal string into Go value of type map[string]interface {}
[英]json: cannot unmarshal string into Go value of type MyMap.map
我遇到了在 golang 中编组 JSON 的问题。
我需要解组从 UDP 数据包收到的 json object。 但是我遇到了解组的问题 - 它不想正确解组。
我收到“解组错误:json:无法将字符串解组为 main.MyMap 类型的 Go 值”错误。 我以不同的方式进行了测试,但感觉卡在了这个例子上——marshaland unmarshal in a line,但仍然会出错。
package main
import (
"encoding/json"
"fmt"
"log"
)
type MyMap struct {
Param map[string]string `json:"packet"`
}
func main() {
rawJson := []byte(`{
"packet":{
"hostname":"host1",
"pid":"123435",
"processname":"process",
"type":"partial"}
}`)
data, err := json.Marshal(rawJson)
if err != nil {
log.Println("Error with marchal JSON: " + err.Error())
}
var unmarshaled MyMap
err = json.Unmarshal(data, &unmarshaled)
if err != nil {
fmt.Printf("Error with unmarshaling: %v", err)
return
}
fmt.Printf("Read a message from %v %s \n", unmarshaled.Param["pid"], unmarshaled.Param["processname"])
}
如果我试图解组从 UDP 收到的 JSON,则错误显示
invalid character 'i/x01' looking for beginning of value
我相信我会因为对元帅系统的误解而得到这种错误。 如果您能帮助我,我将不胜感激谢谢!
我对您的代码进行了一些更改,并且效果很好。
你可以在这里运行它: https://go.dev/play/p/jvw9MsVFbHt
type mp map[string]string
type MyMap struct {
Param mp `json:"packet"`
}
func main() {
rawJson := []byte(`{
"packet":{
"hostname":"host1",
"pid":"123435",
"processname":"process",
"type":"partial"}
}`)
data, err := json.Marshal(rawJson) //Not Required
if err != nil {
fmt.Println("Error with marchal JSON: " + err.Error())
}
fmt.Println("data ", data)
var res MyMap
json.Unmarshal(rawJson, &res)
fmt.Printf("Read a message from %v %s \n", res.Param["pid"], res.Param["processname"])
}
您应该将rawjson
更改为字符串类型并将您的订单代码更改为:
package main
import (
"encoding/json"
"fmt"
)
type MyMap struct {
Param map[string]string `json:"packet"`
}
func main() {
rawJson := `{
"packet":{
"hostname":"host1",
"pid":"123435",
"processname":"process",
"type":"partial"}
}`
struct_instance := MyMap{}
if er := json.Unmarshal([]byte(rawJson), &struct_instance); er != nil {
fmt.Println(er)
}
fmt.Println(struct_instance)
json_as_byte, er := json.Marshal(struct_instance)
if er != nil {
fmt.Println(er)
}
fmt.Println(string(json_as_byte))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.