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

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

在golang中解析沒有索引名稱的json

在golang中解析沒有索引名稱的json

Go
慕婉清6462132 2021-11-01 16:10:29
我有以下格式的json{    "status_code": 200,    "status_message": "OK",    "response": {        "Messages": [            "CODE_NOT_AVAILABLE"        ],        "UnknownDevices": {            "": [                "6",                "7",                "8",                "9",                "10"            ]        }    }}正如我們看到的,我們缺少一個索引鍵,在 unknownDevices 之后,我試圖通過以下方式使用 golan 解組這個 jsonpackage mainimport (    "encoding/json"    "fmt")type pushWooshResponse struct {    Status     int    `json:"status_code"`    Status_msg string `json:"status_message"`    Response   response}type response struct {    Message        []string `json:"Messages"`    UnknownDevices devices}type devices struct {    Udevices []string `json:""`}func main() {    itemInfoR := `{"status_code":200,"status_message":"OK","response":{"Messages":["CODE_NOT_AVAILABLE"],"UnknownDevices":{"devices":["6","7","8","9","10"]}}}`    itemInfoBytes := []byte(itemInfoR)    var ItemInfo pushWooshResponse    er := json.Unmarshal(itemInfoBytes, &ItemInfo)    if er != nil {        fmt.Println("Error", er.Error())    } else {        fmt.Println(ItemInfo)    }}輸出是{200 OK {[CODE_NOT_AVAILABLE] {[]}}}除了最后一部分外,一切都正常,我無法解開這一部分。你能幫我把 json 的最后一部分 umarhal 嗎?
查看完整描述

1 回答

?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

可能還有其他選擇,但是每當您看到奇怪的 JSON 時,您總是可以通過實現json.Unmarshaler和/或json.Marshaler.


也許是這樣的:


type devices struct {

    Udevices []string

}


func (d *devices) UnmarshalJSON(b []byte) error {

    var x map[string][]string

    err := json.Unmarshal(b, &x)

    if err == nil {

        // perhaps check that only a single

        // key exists in the map as well

        d.Udevices = x[""]

    }

    return err

}


func (d devices) MarshalJSON() ([]byte, error) {

    x := map[string][]string{"": d.Udevices}

    return json.Marshal(x)

}


查看完整回答
反對 回復 2021-11-01
  • 1 回答
  • 0 關注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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