簡體   English   中英

json:無法將字符串解組為 MyMap.map 類型的 Go 值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM