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

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

轉到結構 JSON 數組的數組

轉到結構 JSON 數組的數組

Go
月關寶盒 2022-09-19 10:42:43
我在嘗試從特定的請求響應映射一些數據時遇到問題,因為在serialLabels內部:有沒有屬性名稱(int,字符串)的數據,所以我對如何映射該數據感到困惑:這是服務響應:{"data": {    "seriesLabels": [        [            0,            "(none)"        ],        [            0,            "Cerveza"        ],        [            0,            "Cigarros"        ],        [            0,            "Tecate"        ],        [            0,            "Cafe"        ],        [            0,            "Amstel"        ],        [            0,            "Leche"        ],        [            0,            "Ultra"        ],        [            0,            "Coca cola"        ],        [            0,            "Agua"        ]    ]}}我去圖表結構映射該信息是:type PopularWord struct {    Data *Data `json:"data"`}type Data struct {    SeriesLabels []*SeriesLabels `json:"seriesLabels"`}type SeriesLabels struct {    value int32  `json:""`    name  string `json:""`}我做錯了什么?聲明結構的正確方法是什么?
查看完整描述

2 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

seriesLabels是一個 JSON 數組,其元素也是 JSON 數組。


要解析數組的 JSON 數組,您可以在 Go 中使用切片:


type Data struct {

    SeriesLabels [][]interface{}

}

測試它:


var pw *PopularWord

if err := json.Unmarshal([]byte(src), &pw); err != nil {

    panic(err)

}

fmt.Println(pw)

for _, sl := range pw.Data.SeriesLabels {

    fmt.Println(sl)

}

輸出(在Go游樂場上嘗試):


&{0xc000120108}

[0 (none)]

[0 Cerveza]

[0 Cigarros]

[0 Tecate]

[0 Cafe]

[0 Amstel]

[0 Leche]

[0 Ultra]

[0 Coca cola]

[0 Agua]

要將內部數組作為結構值獲取,您可以實現自定義取消封接:


type Data struct {

    SeriesLabels []*SeriesLabels `json:"seriesLabels"`

}


type SeriesLabels struct {

    value int32 

    name  string

}


func (sl *SeriesLabels) UnmarshalJSON(p []byte) error {

    var s []interface{}

    if err := json.Unmarshal(p, &s); err != nil {

        return err

    }

    if len(s) > 0 {

        if f, ok := s[0].(float64); ok {

            sl.value = int32(f)

        }

    }


    if len(s) > 1 {

        if s, ok := s[1].(string); ok {

            sl.name = s

        }

    }

    return nil

}

測試代碼是相同的,輸出(在Go Playground上嘗試這個):


&{0xc0000aa0f0}

&{0 (none)}

&{0 Cerveza}

&{0 Cigarros}

&{0 Tecate}

&{0 Cafe}

&{0 Amstel}

&{0 Leche}

&{0 Ultra}

&{0 Coca cola}

&{0 Agua}



查看完整回答
反對 回復 2022-09-19
?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

問題在于,在 JSON 中將其表示為數組。如果要使用 ,則必須實現取消marshaler接口對其進行解碼(否則它只會接受JSON對象)。SeriesLabelsencoding/json


幸運的是,代碼很簡單:


func (s *SeriesLabels) UnmarshalJSON(d []byte) error {

    arr := []interface{}{&s.value, &s.name}

    return json.Unmarshal(d, &arr)

}

請注意,此代碼將忽略無效輸入(數組太長或類型不正確)。根據您的需要,您可能希望在調用后添加檢查,以確保數組長度和內容(指針)未更改。json.Unmarshal


還有其他用于 Go 的 JSON 解析庫可以使其不那么麻煩,例如 gojay。


查看完整回答
反對 回復 2022-09-19
  • 2 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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