首頁 > 後端開發 > Golang > 主體

為什麼我在 JSON 反序列化期間收到「介面轉換:interface {} is map[string]interface {},而不是 main.Data」錯誤?

Linda Hamilton
發布: 2024-11-14 12:33:02
原創
974 人瀏覽過

Why am I getting an

Interface Conversion Failure during JSON Deserialization

When attempting to deserialize complex data structures from JSON, it's crucial to ensure proper handling of interfaces to avoid runtime errors. Consider the following code:

type Data struct {
    Content string
    Links   []string
}

func main() {
    anInterface := interface{}{/* JSON data here */}

    // Assertion to Data interface
    AData2 := anInterface.(Data)
}
登入後複製

Upon execution, the program throws an error:

panic: interface conversion: interface {} is map[string]interface {}, not main.Data
登入後複製

Understanding the Problem

The error stems from the attempt to assert an interface containing a map of string-interface pairs directly into a Data struct. Go expects the interface to contain a Data value, but the actual content is a map.

Solution

To resolve this issue, it's essential to understand the nature of interfaces. An interface is simply a contract that defines a set of methods a type must implement. To assert an interface to a specific type, the interface must have been previously populated with that type's value.

In this case, the following changes should be made:

  1. Populate the interface with a Data value:
anInterface = Data{Content: "hello world", Links: []string{"link1", "link2", "link3"}}
登入後複製
  1. Assert the interface to Data:
AData2 = anInterface.(Data)
登入後複製

This ensures that the interface contains the correct type before attempting to convert it to Data.

Alternative Approach

Another approach is to directly unmarshal the JSON data into the desired Data structure:

var AData2 Data

err := json.Unmarshal([]byte(jsonStr), &AData2)
if err != nil {
    panic(err)
}
登入後複製

以上是為什麼我在 JSON 反序列化期間收到「介面轉換:interface {} is map[string]interface {},而不是 main.Data」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板