亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 Json 字符串轉換為結構時解析錯誤

將 Json 字符串轉換為結構時解析錯誤

Go
MMTTMM 2022-04-26 15:21:57
我無法解析 json 值我正在發送一個游樂場鏈接你知道嗎?這是鏈接和代碼https://play.golang.org/p/qhZpS_-618spackage mainimport (    "encoding/json"    "fmt"    //mapstructure "github.com/mitchellh/mapstructure")type presence struct{    id string     m_type string     deny string }type jsonHandler struct {    name string     dat map[string]interface{}}   func main() {    s := `["Presence",{"id":"[email protected]","type":"unavailable","deny":true}]`    data := jsonHandler{}    json.Unmarshal([]byte(s), &data)    fmt.Printf("Operation: %s", data.name)}輸出:操作:程序退出。
查看完整描述

3 回答

?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

試試這個: https: //play.golang.com/p/UICf_uNNFdC


為了提高代碼的可讀性,我發表了很多評論。確保正確處理錯誤并刪除調試打印。


package main


import (

    "encoding/json"

    "log"

    "strings"

)


type Presence struct {

    Presence string

    ID       string `json:"id"`

    Type     string `json:"type"`

    Deny     bool   `json:"deny"`

}


type JsonHandler struct {

    Name string   `json:"name"`

    Dat  Presence `json:"dat"`

}


func main() {

    var (

        // Used for unmarshal a given json

        packedData []json.RawMessage

        err        error

        // Data that does not have a related json key

        name []byte

        // Used for extract the raw data that will be unmarshalled into the Presence struct

        temp []byte

        // Nested json

        jsonPresence Presence

        handler      JsonHandler

    )


    s := `["Presence",{"id":"[email protected]","type":"unavailable","deny":true}]`


    log.Println("Dealing with -> " + s)


    // Unmarshall into a raw json message

    err = json.Unmarshal([]byte(s), &packedData)

    if err != nil {

        panic(err)

    }


    // Extract the presence

    log.Println("Presence: ", string(packedData[0]))

    // Extract the nested json

    log.Println("Packed: ", string(packedData[1]))


    // NOTE: 0 refers to the first value of the JSON

    name, err = packedData[0].MarshalJSON()

    if err != nil {

        panic(err)

    }

    log.Println("Value that does not have a key: " + string(name))

    handler.Name = strings.Replace(string(name), "\"", "", -1)


    // NOTE: 1 refers to the second value of the JSON, the entire JSON

    // Unmarshal the nested Json into byte

    temp, err = packedData[1].MarshalJSON()

    if err != nil {

        panic(err)

    }


    // Unmarshal the raw byte into the struct

    err = json.Unmarshal(temp, &jsonPresence)

    if err != nil {

        panic(err)

    }


    log.Println("ID:", jsonPresence.ID)

    log.Println("Type:", jsonPresence.Type)

    log.Println("Deny:", jsonPresence.Deny)


    handler.Dat = jsonPresence


    log.Println("Data unmarshalled: ", handler)

}


查看完整回答
反對 回復 2022-04-26
?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

去游樂場鏈接: https: //play.golang.org/p/qe0jyFVNTH1

這里存在幾個問題:

1. Json 包不能引用未導出的結構元素。因此請在以下代碼段中使用 Deny 而不是拒絕。這適用于結構內聲明的所有變量

2. json 字段標記不正確. 例如。mapstructure:"id"應該是json:"id"

3。要解析的json包含兩個不同的元素,即字符串“Presence”和嵌套的json對象。它不能被解析為單個元素。最好聲明“Presence”為key,嵌套json為價值。

4.拒絕變量應該是bool而不是string


查看完整回答
反對 回復 2022-04-26
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

哇,通過僅添加這些代碼解決了問題


這里去朗鏈接: https: //play.golang.org/p/doHNWK58Cae


func (n *JsonHandler) UnmarshalJSON(buf []byte) error {

    tmp := []interface{}{&n.Name, &n.Dat}

    wantLen := len(tmp)

    if err := json.Unmarshal(buf, &tmp); err != nil {

        return err

    }

    if g, e := len(tmp), wantLen; g != e {

        return fmt.Errorf("wrong number of fields in Notification: %d != %d", g, e)

    }

    return nil

}


查看完整回答
反對 回復 2022-04-26
  • 3 回答
  • 0 關注
  • 229 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號