在我的代碼中,一個方法監聽一個 redis 佇列。我將 Redis 發送的資料作為“有效負載”變數用于以下代碼示例。“currenttime” 變數是 time.time,但 json.unmarshall 將其更改為字串值。我怎樣才能防止這種情況?我想從 currenttime 獲取 time.time 資料。“價值”資料也動態變化。每次都可以更改“count”、“name”和“currenttime”變數名稱。我可以只看價值觀。
type Event struct {
ID string `json:"id"`
Value interface{} `json:"value"`
}
func main() {
payload := "{\"id\":\"61e310f79b9a4db146a8cb7d\",\"value\":{\"Value\":{\"count\":55,\"currenttime\":\"2022-02-23T00:00:00Z\",\"name\":\"numberone\"}}}"
var event Event
if err := json.Unmarshal([]byte(payload), &event); err != nil {
fmt.Println(err)
}
fmt.Println(event)
}
uj5u.com熱心網友回復:
如果Event.Value.Value有一個預定義的結構
使用適當的結構來建模您的輸入 JSON,您可以在其中使用time.TimeJSONcurrenttime屬性:
type Event struct {
ID string `json:"id"`
Value struct {
Value struct {
Count int `json:"count"`
CurrentTime time.Time `json:"currenttime"`
Name string `json:"name"`
} `json:"Value"`
} `json:"value"`
}
像這樣列印:
fmt.Println(event)
fmt.Printf("% v\n", event)
fmt.Printf("%T %v\n", event.Value.Value.CurrentTime, event.Value.Value.CurrentTime)
輸出是(在Go Playground上試試):
{61e310f79b9a4db146a8cb7d {{55 2022-02-23 00:00:00 0000 UTC numberone}}}
{ID:61e310f79b9a4db146a8cb7d Value:{Value:{Count:55 CurrentTime:2022-02-23 00:00:00 0000 UTC Name:numberone}}}
time.Time 2022-02-23 00:00:00 0000 UTC
如果Event.Value.Value沒有預定義的結構
如果 的屬性Event.Value.Value可以動態更改,請使用 map ( map[string]interface{}) 解組。由于我們不能告訴這個時間我們想要一個time.Time值(其他屬性不保存時間值),時間欄位將被解組為string. 所以你必須迭代它的值并嘗試用正確的布局決議這些值。如果將其決議為時間成功,我們就有了我們想要的。
這是它的樣子:
type Event struct {
ID string `json:"id"`
Value struct {
Value map[string]interface{} `json:"Value"`
} `json:"value"`
}
func main() {
payload := "{\"id\":\"61e310f79b9a4db146a8cb7d\",\"value\":{\"Value\":{\"foo\":55,\"mytime\":\"2022-02-23T00:00:00Z\",\"bar\":\"numberone\"}}}"
var event Event
if err := json.Unmarshal([]byte(payload), &event); err != nil {
fmt.Println(err)
}
for _, v := range event.Value.Value {
if s, ok := v.(string); ok {
t, err := time.Parse("2006-01-02T15:04:05Z", s)
if err == nil {
fmt.Println("Found time:", t)
}
}
}
}
這將輸出(在Go Playground上嘗試):
Found time: 2022-02-23 00:00:00 0000 UTC
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/466890.html
