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

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

json: cannot unmarshal string into Go value of type MyMap.map

问题

我在使用golang中的JSON编组时遇到了问题。

我需要解组来自UDP数据包的JSON对象。但是我在解组时遇到了问题 - 它无法正确解组。

我得到了"Error with unmarshaling: json: cannot unmarshal string into Go value of type main.MyMap"的错误。
我尝试了不同的方法,但是在这个例子中我感到困惑 - 在一行中进行编组和解组,仍然出现错误。

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

我相信我之所以会遇到这种错误,是因为我对编组系统的理解有误。
如果你能帮助我,我将不胜感激。
谢谢!

英文:

I met problem with marshaling JSON in golang.

I need to unmarshal json object, that I recieve from UDP packets.
But I met problem with unmarshaling - it doesn't want to unmarshal properly.

I get "Error with unmarshaling: json: cannot unmarshal string into Go value of type main.MyMap" error.
I tested in different ways, but feel stuck on this example - marshaland unmarshal in one line, and still get errors.

    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"])
}

If I'm trying to unmarshal JSON, that I received from UDP, the error says

invalid character 'i/x01' looking for beginning of value

I believe I get this kind of error because of my misunderstanding of marshal system.
I'd be appreciate if you help me
Thanks!

答案1

得分: 0

我对你的代码进行了一些更改,它运行得非常好。

你可以在这里运行它: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)     //不需要这行
    if err != nil {
        fmt.Println("Error with marshal 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"])
}

这是你要翻译的内容。

英文:

I did few changes in your code and it's worked very well.

You can run it here: 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"])
}

答案2

得分: 0

你应该将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))

}
英文:

you should change rawjson to string type and change your order code same as:

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))

}


huangapple
  • 本文由 发表于 2021年12月7日 21:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/70261269.html
匿名

发表评论

匿名网友

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

确定