我以為我現在了解解組,但我想沒有。我在解組地圖時遇到了一些麻煩。這是我到目前為止的代碼
type OHLC_RESS struct {
Pair map[string][]Candles
Last int64 `json:"last"`
}
type Candles struct {
Time uint64
Open string
High string
Low string
Close string
VWAP string
Volume string
Count int
}
func (c *Candles) UnmarshalJSON(d []byte) error {
tmp := []interface{}{&c.Time, &c.Open, &c.High, &c.Low, &c.Close, &c.VWAP, &c.Volume, &c.Count}
length := len(tmp)
err := json.Unmarshal(d, &tmp)
if err != nil {
return err
}
g := len(tmp)
if g != length {
return fmt.Errorf("Lengths don't match: %d != %d", g, length)
}
return nil
}
func main() {
response := []byte(`{"XXBTZUSD":[[1616662740,"52591.9","52599.9","52591.8","52599.9","52599.1","0.11091626",5],[1616662740,"52591.9","52599.9","52591.8","52599.9","52599.1","0.11091626",5]],"last":15}`)
var resp OHLC_RESS
err := json.Unmarshal(response, &resp)
fmt.Println("resp: ", resp)
}
運行代碼后,該last欄位將很好地解組,但無論出于何種原因,地圖都沒有任何價值。有什么幫助嗎?
uj5u.com熱心網友回復:
對于特定示例 JSON,權宜之計的解決方案是根本不使用地圖,而是更改結構OHLC_RESS,使其與 JSON 的結構相匹配,即
type OHLC_RESS struct {
Pair []Candles `json:"XXBTZUSD"`
Last int64 `json:"last"`
}
https://go.dev/play/p/Z9PhJt3wX33
但是,我認為可以安全地假設您選擇使用映射的原因是因為保存“對”的 JSON 物件的鍵可能會有所不同,因此將它們硬編碼到欄位的標簽中是不可能的.
要了解為什么您的代碼沒有產生預期的結果,您必須了解兩件事。首先,結構欄位的順序與JSON 物件的鍵如何被解碼無關。其次,該名稱對Pair解組器沒有特殊意義。因此,默認情況下,解組器無法知道您希望將"XXBTZUSD": [ ... ]元素解碼到Pair映射中。
因此,為了獲得您想要的結果,您可以OHLC_RESS實作json.Unmarshaler介面并執行以下操作:
func (r *OHLC_RESS) UnmarshalJSON(d []byte) error {
// first, decode just the object's keys and leave
// the values as raw, non-decoded JSON
var obj map[string]json.RawMessage
if err := json.Unmarshal(d, &obj); err != nil {
return err
}
// next, look up the "last" element's raw, non-decoded value
// and, if it is present, then decode it into the Last field
if last, ok := obj["last"]; ok {
if err := json.Unmarshal(last, &r.Last); err != nil {
return err
}
// remove the element so it's not in
// the way when decoding the rest below
delete(obj, "last")
}
// finally, decode the rest of the element values
// in the object and store them in the Pair field
r.Pair = make(map[string][]Candles, len(obj))
for key, val := range obj {
cc := []Candles{}
if err := json.Unmarshal(val, &cc); err != nil {
return err
}
r.Pair[key] = cc
}
return nil
}
https://go.dev/play/p/Lj8a8Gx9fWH
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479608.html
上一篇:設定自定義物件的地圖輸出c
