簡體   English   中英

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

[英]json: cannot unmarshal object into Go value of type Auction.Item

我在反序列化對象時遇到問題。 我使用此對象的接口來調用序列化,並且從讀取輸出中可以很好地實現序列化。 這是我對象的基礎結構:

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

任何幫助表示贊賞。

BidItem編組者不知道用於nil BidItem域的具體類型。 您可以通過將字段設置為適當類型的值來解決此問題:

func PimpFromJSON(content []byte) (Pimp, error) {
    p := new(pimp)
    p.BidItem = &item{}
    err := json.Unmarshal(content, p)
    return p, err
}

游樂場的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM