」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Go 中使用自訂 UnmarshalJSON 處理嵌入式結構?

如何在 Go 中使用自訂 UnmarshalJSON 處理嵌入式結構?

發佈於2024-11-09
瀏覽:421

How to Handle Embedded Structs with Custom UnmarshalJSON in Go?

錯誤處理:嵌入式結構的自訂解組

在Go 中,當將JSON 資料解組到具有嵌入式欄位的結構時,如果嵌入式結構定義了自己的UnmarshalJSON 方法。這是因為 JSON 函式庫呼叫嵌入結構的 UnmarshalJSON 並忽略包含結構中定義的欄位。

案例研究

考慮以下結構定義:

type Outer struct {
    Inner
    Num int
}

type Inner struct {
    Data string
}

func (i *Inner) UnmarshalJSON(data []byte) error {
    i.Data = string(data)
    return nil
}

當使用 json.Unmarshal(data, &Outer{}) 將 JSON 解組到 Outer 時,Inner 欄位會觸發其 UnmarshalJSON 方法,消耗整個 JSON 字串。這會導致 Outer 中的 Num 欄位被忽略。

解決方案:明確欄位

要解決此問題,請將嵌入的struct Inner 轉換為Outer 中的明確欄位:

type Outer struct {
    I Inner // make Inner an explicit field
    Num int `json:"Num"`
}

透過將 Inner 設為明確字段,您可以確保 JSON 庫將資料解組到 Outer 的相應字段中,包括 Num 字段。

範例

import (
    "encoding/json"
    "fmt"
)

type Outer struct {
    I Inner // make Inner an explicit field
    Num int `json:"Num"`
}

type Inner struct {
    Data string
}

func (i *Inner) UnmarshalJSON(data []byte) error {
    i.Data = string(data)
    return nil
}

func main() {
    data := []byte(`{"Data": "Example", "Num": 42}`)
    var outer Outer
    err := json.Unmarshal(data, &outer)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(outer.I.Data, outer.Num) // Output: Example 42
}
最新教學 更多>

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

Copyright© 2022 湘ICP备2022001581号-3