1 回答

TA貢獻1856條經驗 獲得超11個贊
如果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"`
}
像這樣打?。?/p>
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[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
- 1 回答
- 0 關注
- 228 瀏覽
添加回答
舉報