亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

json:無法將對象解組為 Auction.Item 類型的 Go 值

json:無法將對象解組為 Auction.Item 類型的 Go 值

Go
慕無忌1623718 2022-03-07 16:02:25
我在反序列化我的對象時遇到問題。我使用該對象的接口來調用序列化,并且通過讀取輸出,序列化工作完美。這是我的對象的底層結構:type pimp struct {    Price       int    ExpDate     int64    BidItem     Item    CurrentBid  int    PrevBidders []string}這是它實現的接口:type Pimp interface {    GetStartingPrice() int    GetTimeLeft() int64    GetItem() Item    GetCurrentBid() int    SetCurrentBid(int)    GetPrevBidders() []string    AddBidder(string) error    Serialize() ([]byte, error)}Serialize() 方法:func (p *pimp) Serialize() ([]byte, error) {    return json.Marshal(*p)}您可能已經注意到,pimp 有一個名為 Item 的變量。這個項目也是一個接口:type item struct {    Name string}type Item interface {    GetName() string}現在序列化此類對象的樣本會返回以下 JSON:{"Price":100,"ExpDate":1472571329,"BidItem":{"Name":"ExampleItem"},"CurrentBid":100,"PrevBidders":[]}這是我的反序列化代碼:func PimpFromJSON(content []byte) (Pimp, error) {    p := new(pimp)    err := json.Unmarshal(content, p)    return p, err}但是,運行它會給我以下錯誤:json: cannot unmarshal object into Go value of type Auction.Item任何幫助表示贊賞。
查看完整描述

1 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

unmarshaler 不知道用于 nilBidItem字段的具體類型。您可以通過將字段設置為適當類型的值來解決此問題:


func PimpFromJSON(content []byte) (Pimp, error) {

    p := new(pimp)

    p.BidItem = &item{}

    err := json.Unmarshal(content, p)

    return p, err

}


查看完整回答
反對 回復 2022-03-07
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號