」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Go 中將巢狀 JSON 解組到物件數組中?

如何在 Go 中將巢狀 JSON 解組到物件數組中?

發佈於2024-12-21
瀏覽:595

How to Unmarshal Nested JSON into an Array of Objects in Go?

將嵌套 JSON 解組到 Go 中的物件陣列中

問題

考慮以下 JSON 資料:

{
   "1001":{
      "level":10,
      "monster-id":1001,
      "skill-level":1,
      "aimer-id":301
   },
   "1002":{
      "level":12,
      "monster-id":1002,
      "skill-level":1,
      "aimer-id":302
   },
   "1003":{
      "level":16,
      "monster-id":1003,
      "skill-level":2,
      "aimer-id":303
   }
}

目標是將這個 JSON 解組到 Monster 物件陣列中。

type Monster struct {
    MonsterId  int32
    Level      int32
    SkillLevel int32
    AimerId    int32
}

解決方案

要實現此目的,請按照下列步驟操作:

  1. 定義MonsterCollection: 建立一個MonsterCollection 類型來儲存Monster 的地圖帶有字串鍵的物件。
type MonsterCollection struct {
    Pool map[string]Monster
}
  1. 實作 FromJson 方法: 在 MonsterCollection 類型上定義 FromJson 方法來處理解群組。
func (mc *MonsterCollection) FromJson(jsonStr string) error {
    var data *map[string]Monster
    b := []byte(jsonStr)
    return json.Unmarshal(b, &data)
}
  • 使用 var data *map[string]Monster 避免使用 interface{},確保產生的映射具有所需的類型。
  • 將資料作為指標傳遞可確保解組期間所做的變更會反映在 MonsterCollection 的池欄位中。
  1. 正確的密鑰類型in Pool: 將 Pool 映射的鍵類型更改為字串,以匹配 JSON 資料中的鍵。
  2. 使用結構標籤: 將 JSON 結構標籤新增至 Monster 結構中指定 JSON 資料中的欄位名稱。
type Monster struct {
    MonsterId  int32 `json:"monster-id"`
    Level      int32 `json:"level"`
    SkillLevel int32 `json:"skill-level"`
    AimerId    int32 `json:"aimer-id"`
}
  1. Call FromJson: 使用 JSON 字串呼叫 FromJson 方法,將資料解組到 MonsterCollection 中。
mc := new(MonsterCollection)
err := mc.FromJson(jsonStr)
  1. 檢查錯誤: 處理 FromJson 傳回的任何錯誤以進行偵錯。
  2. 存取物件: 使用 MonsterCollection 的 Pool 欄位來存取各個 Monster 物件。
for id, monster := range mc.Pool {
    fmt.Println(id, monster)
}

依照下列步驟,您可以成功地將嵌套的 JSON 資料解組到 Go 中的 Monster 物件陣列中。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3